1

我有我创建的 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
4

2 回答 2

1

我看不出您的代码有任何问题,因此这可能是 Refile 中的错误。我唯一可以建议的是使用自定义验证器。

validate :csv_extension

private

def csv_extension
  unless csv_content_type == "text/csv"
    errors.add :csv, "format must be csv" # might want to use i18n here.
  end
end

您可能想改用文件扩展名,因为content_type有时它不可用。

def csv_extension
  unless File.extname(csv_filename) == "csv"
    errors.add :csv, "format must be csv"
  end
end

我不会在这些东西上信任客户端,但即使 Refile 也依赖于客户端,content_type所以它几乎没有什么不同。

于 2015-10-18T13:41:06.657 回答
0

所以最终出现了几个问题。

首先,控制器中的强参数应该如下所示,

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。

于 2015-10-22T01:30:08.037 回答