Best way to upload an image with POST? Base64?

  • 21
    Just plain old "multipart/form-data" in JS with "new Formdata() etc. (see MDN FormData)
    Or JSON with base64
  • 5
    Depending on the JS framework you use, you need to set the appropriate headers as well (for "multipart/form-data")

  • 4
    @PonySlaystation I’m also sending the details so I’m putting it inside JSON, is there any downside for this? Character limitation?
  • 3
    @devTea not really a limit. I think it depends on the server.
    Do you have a specification which content-type you need to send?

    "multipart/form-data" is mostly the easiest, as you either send an existing HTML form or create the FormData in JS.

    The JSON approach may be "cleaner", if you want to keep everything communicating in JSON. 😉

    I personally prefer FormData, if I have to send files, but I've had to do it in JSON with base64 once.
  • 6
    The easiest way depends on the framework I guess... In Vue, I've gone for a base64-based upload, which is awesome as you can use it to validate the content client-side before uploading ánd instantly update or preview the uploaded content without any extra request.

    It also depends on what kind of stuff you'd want to upload, an avatar makes base64 a no-brainer, though base64 has its size against it for other stuff.

    And the way you want to post and catch the response... Not sure how or if Ajax requests handle actual multipart to be sent.. ö
  • 4
    @PonySlaystation I wouldn't do a json. If there is an unmarshaller st server reading that json into an object there will be many uneccessary bufferings and rebufferings. Impossible to make that img a stream and pass it to lower layers. Not to mention unmarshallers are usualy vulnerable to payload size based dos attacks.

    I'd say multipart is the way.
  • 1
    Our Drupal systems exchange images (as well as other media types like videos, audios or pdfs) with our apps as base64 as these systems exchange every data as JSON
  • 2
    i think FormData is the easiest way
  • 3
    @PonySlaystation @xewl @netikras @xic3fox @KorDarei thanks I’ll look into both options
  • 2
    What’s the data type for backend to read? Nvarchar got a limit of 255 characters
  • 1
    I'd say it depends on your backend application that receives the file. If you just want to save the file in PHP for example you could base64_decode($bas64file) and save it with file_put_contents. If you want to save it to a database I'd probably use BLOB or TEXT (I'm not quite sure how to use BLOB tho)
  • 2
    @xic3fox it’s pass through node.js to amazon s3
Your Job Suck?
Get a Better Job
Add Comment