fileupload form_tag rails时出现问题

时间:2013-10-07 06:32:22

标签: ruby-on-rails ruby-on-rails-3 file-upload

当我通过POST查询到API使用form_tag进行fileupload时,我遇到了麻烦。 当我使用时:

= form_tag("http://myapi.com/api/images/user/#{@user_id}", multipart: true) do
 = file_field_tag 'upload'
 = submit_tag 'Upload avatar'

我没有麻烦。但是当我尝试使用update_avatar的动作时,我遇到了麻烦。

= form_tag({:action => 'upload_avatar'}, multipart: true) do
 = file_field_tag 'upload'
 = submit_tag 'Upload avatar'

update_avatar动作代码:

def upload_avatar
    @user_id = params[:id]
    @post_params =  {'upload' => params[:upload]}
    response, data = Net::HTTP.post_form(URI.parse("http://myapi.com/api/images/user/#{@user_id}"),  @post_params)
    redirect_to users_path
end

回应是:

#<Net::HTTPInternalServerError:0x007f331486f4e0> 

数据是:nil

1 个答案:

答案 0 :(得分:1)

Here是3种上传文件的方式

require "net/http"
require "uri"

# Token used to terminate the file in the post body. Make sure it is not
# present in the file you're uploading.
BOUNDARY = "AaB03x"

uri = URI.parse("http://something.com/uploads")
file = "/path/to/your/testfile.txt"

post_body = []
post_body << "--#{BOUNDARY}\r\n"
post_body << "Content-Disposition: form-data; name=\"datafile\"; filename=\"#{File.basename(file)}\"\r\n"
post_body << "Content-Type: text/plain\r\n"
post_body << "\r\n"
post_body << File.read(file)
post_body << "\r\n--#{BOUNDARY}--\r\n"

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request.body = post_body.join
request["Content-Type"] = "multipart/form-data, boundary=#{BOUNDARY}"

http.request(request)

# Alternative method, using Nick Sieger's multipart-post gem
require "rubygems"
require "net/http/post/multipart"

reqest = Net::HTTP::Post::Multipart.new uri.request_uri, "file" => UploadIO.new(file, "application/octet-stream")
http = Net::HTTP.new(uri.host, uri.port)
http.request(request)

# Another alternative, using Rack 1.3 +
require 'rack'
uri     = URI.parse("http://something.com/uploads")
http    = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)

request.body = Rack::Multipart::Generator.new(
  "form_text_field" => "random text here",
  "file"            => Rack::Multipart::UploadedFile.new(path_to_file, file_mime_type)
).dump
request.content_type = "multipart/form-data, boundary=#{Rack::Multipart::MULTIPART_BOUNDARY}"

http.request(request)

http.start do |connection|
  response = retrying_request(connection, request)
end