我创建了Rails应用程序,因此可以使用API部分。我可以使用curl成功地将文件上传到rails应用程序的数据库,但是我不知道如何将文件类型/内容类型限制为仅CSV。
csv_file.rb#模型
class CsvFile < ActiveRecord::Base
# attachment :content_type => "text/csv"
# http://ryanbigg.com/2009/04/how-rails-works-2-mime-types-respond_to/
attachment :csv, extension: "csv", content_type: "text/csv"
end
csv_files.rb#控制器
class API::V1::CsvFilesController < ApplicationController
# see http://stackoverflow.com/questions/15040964/ for explanation
skip_before_filter :verify_authenticity_token
def index
@csv_files = CsvFile.all
if @csv_files
render json: @csv_files,
# each_serializer: PictureSerializer,
root: "csv_files"
else
@error = Error.new(text: "404 Not found",
status: 404,
url: request.url,
method: request.method)
render json: @error.serializer
end
end
def show
if @csv_file
render json: @csv_file,
# serializer: PictureSerializer,
root: "csv_file"
else
@error = Error.new(text: "404 Not found",
status: 404,
url: request.url,
method: request.method)
render json: @error.serializer
end
end
# POST /csv_files.json
def create
@csv_file = CsvFile.new(csv_params)
if @csv_file.save
render json: @csv_file,
# serializer: PictureSerializer,
meta: { status: 201,
message: "201 Created"},
root: "csv_file"
else
@error = Error.new(text: "500 Server Error",
status: 500,
url: request.url,
method: request.method)
render :json => @error.serializer
end
end
def update
end
def delete
end
private
def csv_params
end
end
因此最终出现了两个问题。
首先,控制器中的强参数应如下所示:
def csv_params
params.permit(:csv_file)
end
其次,我需要像这样在迁移中添加一列,
add_column :csv_files, :csv_file_id, :string
最后,我能够修改csv_file.rb
模型文件并添加以下行。
attachment :csv_file, extension: "csv"
目前,只能将扩展名为的文件.csv
上传到API。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句