简体   繁体   中英

POSTing json data and file to Ruby on Rails API

I'm very new to ruby on rails, so its likely that I'm missing something simple, but I can't figure this out for the life of me.

I have created an API server with ruby on rails, and I can't seem to be able to post JSON along with a picture. I keep receiving an error on the server side, complaining about the encoding being wrong.

ActionController::BadRequest (Invalid request parameters: invalid %-encoding 
.rbenv/versions/3.0.1/lib/ruby/3.0.0/uri/common.rb:324:in decode_www_form_component'

I am using Postman to make the request. I am using the form-data option to include a text entry with my JSON, and a file entry with my PNG. The header Content-Type is multipart/mixed. And the individual key/value pairs are application/json and image/png respectively. I can't tell if this is a postman issue, a ruby controller issue. or a bug.

邮递员请求图片

后定义

必填字段

Any insight or further questions will help me.

EDIT: Here is the code from my post request from inside postman.

curl --location --request POST 'http://localhost:3000/api/v1/events/1/eventphotos/' \
--header 'Content-Type: multipart/mixed' \
--form 'data={
    "eventphoto":{
        "event_id":1,
        "photopath":"nothing to see here"
    }
}' \
--form 'picture=@/Users/chancefinley/Downloads/mushroom.png'

I'm not sure if it's the case, but have you added active storage to your project? because if not, I think it's having trouble inserting the file into the database, you could transform the image into base 64 encoding and save it as a string or follow this guide and see if it helps: https://levelup.gitconnected.com/rails-image-upload-101-f9bf245e389b

Problem ended up being that I needed a view which would contain a form. You know, so that the formdata request has something to actually submit to...... Dumb mistake. Learned my lesson

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM