简体   繁体   中英

Posting a file using Json

I want to upload a binary file using json. I choose Json because with the file I would also like to send additional information.

I am going to do this by -

  1. Select a file in the file input tag.
  2. Use the HTML5 File Reader Api to read a file first.
  3. Convert the file content into base64.
  4. Add the base64 content to a JS object in a data uri format.
  5. Convert the JS object to json and post it to the server.

I wonder if this is the only legitimate way to achieve my goal? Also, if there is a plugin already available somewhere which give me this ability?

No, this is not the only way - one of the other ways is just to submit a form with a file in it. Such form uses multipart/form-data content type.

See W3C documentation on the subject :

The content type " application/x-www-form-urlencode d" is inefficient for sending large quantities of binary data or text containing non-ASCII characters.

The content type " multipart/form-data " should be used for submitting forms that contain files, non-ASCII data, and binary data.

So, there is no need to reinvent the wheel - browsers already support sending the files along with additional information, in a simple way. You just create a form where the user can enter data and select files, then all of them are sent to the server with multipart/form-data content type, and your web framework should be able to understand that it deals with both files and textual data.

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