Trouble when fileupload form_tag rails -
i have trouble when use form_tag fileupload via post query api. when use:
= form_tag("http://myapi.com/api/images/user/#{@user_id}", multipart: true) = file_field_tag 'upload' = submit_tag 'upload avatar'
i have no troubles. when try use action update_avatar, have trouble.
= form_tag({:action => 'upload_avatar'}, multipart: true) = file_field_tag 'upload' = submit_tag 'upload avatar'
update_avatar action code:
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
response is:
#<net::httpinternalservererror:0x007f331486f4e0>
data is: nil
here 3 ways upload file
require "net/http" require "uri" # token used terminate file in post body. make sure not # present in 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) # 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 |connection| response = retrying_request(connection, request) end
Comments
Post a Comment