1

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

= 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> 

数据为:无

4

1 回答 1

1

这里有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
于 2013-10-07T07:54:40.430 回答