上传文件产生406(不可接受)错误

时间:2012-06-23 01:35:17

标签: ruby ruby-on-rails-3

我正在尝试使用示例代码上传文件。我没有收到任何编译错误,但出现406 Not Acceptable错误消息。这是什么意思?

POST请求:

Started POST "/files/upload" for 10.15.24.38 at 2012-06-22 21:18:11 -0400
Processing by FilesController#upload as HTML
  Parameters: {"utf8"=>"â", "authenticity_token"=>"wfpBi3Y8KgmqitXrh4fZ3xfun73mWOfXiTQ+J7bdfWU=", "user_id"=>"231",
"button"=>"", "upload"=>{"datafile"=>"ws_1920x1080.jpg"}}

查看:

<%= form_tag files_upload_path, :remote => true, :method => :post, :multipart => true do %>
#The form has some other values too. I am keeping it short here.  
<p>
<label for="upload_file">Select File</label> :
<%= file_field 'upload', 'datafile' %>
</p>
<% end %>

控制器:

 def upload
    #The controller has some other values too, that are not related to file upload. 

    if params[:datafile]
    uploaded_io = params[:upload][:datafile]
    File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
    file.write(uploaded_io.read)
    end
    end

    if params[:user_id] 
    #do some extra stuff
    end 

    respond_to do |format|
    format.js
    end 

 end

错误:

Completed 406 Not Acceptable in 2736ms (ActiveRecord: 3.2ms)

3 个答案:

答案 0 :(得分:0)

没有足够的信息来提供答案,但您在:multipart => true电话中明显遗漏了form_for,如下所示:

<%= form_for @upload, :multipart => true do |f| %>
  Your form code here
<% end %>

发生了不可接受的错误,因为您要求HTML呈现,但可能没有respond_to部分回复HTML。

答案 1 :(得分:0)

您不允许(以直接方式)通过远程请求上传文件。看看这里:How can I upload files asynchronously?

答案 2 :(得分:0)

我猜你不能使用ajax使用remote => true上传文件,只需指定remotipart你需要某种类型的插件或其类似的内容,如

pluploaduploadifyremote => true或类似内容。

因此,如果您没有使用任何插件,那么即使您指定XMLHttpRequest,该表单也会以普通HTML请求而不是 format.html

发送

现在,在您的控制器中,您已已删除

ajax部分,因为您假设它是406 Not Acceptable请求,但实际上它不是(HTML请求)

becoz Rails无法找到适当的格式来回复报告request.xhr?

请自己帮忙记录控制器中的logger.info "******************** #{request.xhr?} *********************"方法。

类似

request.xhr?

如果{{1}}返回 nil 指定该请求 ajax请求