api上传multipartform-data

问题描述 投票:0回答:1

运行下面的post请求时,我的@post.picture控制器保存Carrierwave postman

def create
  @post = Post.new(post_params) 
  respond_to do |format|
    if @post.save
       # .... all the json/html responses
    end
  end
end

def post_params   
  params.require(:post).permit(:description, :picture)
end

邮递员

POST /posts.json
X-User-Email: [email protected]
X-User-Token: EBNbDysWKEYqURfpDkWo
Accept: application/json
Content-Type: multipart/form-data; boundary=--------------------------329710892316545763789878
undefined:
cache-control: no-cache
Postman-Token: e320b3bf-c5f3-4e40-a149-fd0323881ec0
User-Agent: PostmanRuntime/7.6.0
Host: 192.168.1.104:3000
accept-encoding: gzip, deflate
content-length: 586600
post[picture]=[object Object]post[description]=test
HTTP/1.1 201
status: 201
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
Location: http://192.168.1.104:3000/posts/15
ETag: W/"540dd0914ae94bd0214825e73955bbde"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: ad99898b-31db-46e0-8a4d-3fc82dafd1c1
X-Runtime: 128.284019
Transfer-Encoding: chunked
{"id":15,"description":"test","picture": {
    "url":"/uploads/Screenshot_from_2019-01-01_16-10-05.png","thumb":{
         "url":"/uploads/thumb_Screenshot_from_2019-01-01_16-10-05.png"
         },"card":{
         "url":"/uploads/card_Screenshot_from_2019-01-01_16-10-05.png"
         }
    },}

enter image description here

这是从服务器获取的rails params

{"post"=>
  {"picture"=>
     #<ActionDispatch::Http::UploadedFile
        @tempfile=#<Tempfile:/tmp/RackMultipart20190115-10912-1rryjxd.png>,
        @original_filename="Screenshot from 2019-01-01 16-10-05.png", 
        @content_type="image/png", 
        @headers="Content-Disposition: form-data; name=\"post[picture]\"; filename=\"Screenshot from 2019-01-01 16-10-05.png\"\r\nContent-Type: image/png\r\n">,},}

我通过AJAX提交以下表单数据

enter image description here

Rails服务器将params处理为

{"post"=>{"picture"=> {
  "path"=>"file:///data/user/0/com.surfapp/cache/Camera/9bc15acd-01d2-4539-a930-f129d72c3dcf.jpg", 
  "name"=>"test.png", 
   "type"=>"image/png"
           }
     }
}
javascript ruby-on-rails carrierwave multipartform-data rails-api
1个回答
0
投票

我采用了following solution进行了几处修改:

我创建了一个Upload::Cache类,它继承自ruby类Tempfile和继承自Upload::Image类的Upload类。

回调set_pictureposts controller create action之前触发,并在@post之前将图像添加到saving

Specs coverage用于此功能

© www.soinside.com 2019 - 2024. All rights reserved.