我对carrierwave gem有疑问。 Extension_whitelist似乎不起作用。
def extension_whitelist
%w(csv)
end
我不知道为什么它不起作用。我导入的文件类型无关紧要,它永远不会引发错误。 这是我的其余代码:
class AttachmentUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_whitelist
%w(csv)
end
end
和控制器(基本上清晰的脚手架有格式和响应)
class PackagesController < ApplicationController
before_action :set_package, only: [:show, :edit, :update, :destroy]
# GET /packages
# GET /packages.json
def index
@packages = Package.all
end
# GET /packages/1
# GET /packages/1.json
def show
end
# GET /packages/new
def new
@package = Package.new
end
# GET /packages/1/edit
def edit
end
# POST /packages
# POST /packages.json
def create
@package = Package.new(package_params)
respond_to do |format|
if @package.save
format.html { redirect_to @package, notice: 'Package was successfully created.' }
format.json { render :show, status: :created, location: @package }
else
format.html { render :new }
format.json { render json: @package.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /packages/1
# PATCH/PUT /packages/1.json
def update
respond_to do |format|
if @package.update(package_params)
format.html { redirect_to @package, notice: 'Package was successfully updated.' }
format.json { render :show, status: :ok, location: @package }
else
format.html { render :edit }
format.json { render json: @package.errors, status: :unprocessable_entity }
end
end
end
# DELETE /packages/1
# DELETE /packages/1.json
def destroy
@package.destroy
respond_to do |format|
format.html { redirect_to packages_url, notice: 'Package was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_package
@package = Package.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def package_params
params.require(:package).permit(:name, :description, :category_id)
end
end
寻找答案我也看到了:
def content_type_whitelist
/csv\//
end
但它也不起作用。 任何想法可能是什么问题? 另外,还有其他简单的方法可以实现吗?
@EDIT问题已经解决:很久以前我报告了这个bug,并且最近修复了。
答案 0 :(得分:2)
该方法需要调用extension_white_list
而不是extension_whitelist
。
在主分支上最近已将其重命名为extension_whitelist
(请参阅commit),但此更改尚未成为公开发布的宝石。
答案 1 :(得分:0)
您可以在模型中使用它
validates_attachment_content_type :attachment, :content_type => 'text/plain'
还可以在此处找到您想要列入白名单的文件类型的完整列表http://www.sitepoint.com/web-foundations/mime-types-complete-list/
答案 2 :(得分:0)
查看您的评论,您正在寻找File_validators gem: https://github.com/musaffa/file_validators
您可以在上传之前验证文件(大小和内容类型)。