Curl请求将映像从本地计算机上载到rails应用程序上的ruby

时间:2012-07-09 19:14:31

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

我在rails上使用ruby构建了一个应用程序。我需要将curl请求发布到该应用程序以从本地计算机上传图像。在我的ruby on rails应用程序中,我使用paperclip进行图像上传。

现在这个卷曲请求工作正常,因为此卷曲请求没有上传图像:

  curl -v -H   "Accept: application/json" -H "Content-type: application/json" -X PUT -d '{"user":{"first_name":"John","last_name":"Smith"},"token":"api"}'  http://localhost:3000/users/8

现在我想从本地机器上传图片。

添加“display_photo”:@ test.jpg不起作用:这就是我的尝试:(但它不能正常工作。)

  curl -v -H  -F "Accept: application/json" -H "Content-type: application/json" -X PUT -d '{"user":{"first_name":"firstname","last_name":"lastname","display_photo":@test.jpg},"token":"api"}'  http://localhost:3000/users/8

所以问题是如何从curl请求上传图像/数据文件/视频

修改

这是我的控制者:

   def update
    @user = User.find(params[:id])

    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html {  redirect_to(@user, :notice => 'User was successfully updated.') }
        format.json  { render :file => "users/json/show.json.erb", :content_type => 'application/json' }
      else
        format.html { render :action => "edit" }
        format.json  { 
          @errors_object = @user
          render :file => "shared/json/errors.json.erb", :content_type => 'application/json' }
      end
    end
  end

在我的模特中:

class User < ActiveRecord::Base
    has_attached_file :display_photo, :styles => { :medium => "200x200#", :thumb => "100x100#", :very_small=>"24x24#" }
end

3 个答案:

答案 0 :(得分:13)

您通常会上传这样的文件:

curl -i -F filedata=@upload.txt http://localhost:5000/

这样做会模仿您通过webbrowsers文件上传时的行为。

如果您查看rails响应,则通过application/octet-stream发送,可以作为上传文件正确处理。据我所知,用json请求不可能做到这一点:

Started POST "/" for 127.0.0.1 at 2012-07-10 09:40:59 +0200
Processing by HomeController#index as */*
  Parameters: {"filedata"=>#<ActionDispatch::Http::UploadedFile:0x007f82d59a3580 @original_filename="upload.txt", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"filedata\"; filename=\"upload.txt\"\r\nContent-Type: application/octet-stream\r\n", @tempfile=#<File:/var/folders/f_/wjnrg7cd3d9f1tpy3k5fhrwm0000gn/T/RackMultipart20120710-30471-1t9abns>>}

答案 1 :(得分:6)

我遇到了同样的问题,我解决了以下问题,绕过了JSON请求:

curl -v -H 'Content-Type: multipart/form-data' -H 'Accept: application/json' -H 'x-api-key:myapikey' -F "user[first_name]=firstname" -F "user[last_name]=lastname" -F "user[display_photo]=@test.jpg" http://localhost:3000/users/8 

答案 2 :(得分:0)

curl -v -include --form "<param>=@/<root>/image_name.png" http://<your url>
**<param>**: The image parameter of the url;
**<root>**: You can use pwd get image root;
**<your url>**: Post url;