Qqwy
Qqwy

Reputation: 5629

Submit a file as part of a jQuery post AJAX request

I am trying to submit a file (together with multiple other normal POST data) to a webserver using a jQuery $.post request.

I saw questions such as this one, but I believe it is outdated, as in the HTML5 era, things like the Web File API exist.

This works great when working with text files. However, when I want to submit binary data such as pictures in this way, the content is changed and sent as text, corrupting it.

So for the question: How can I submit a file using jQuery's AJAX functions as part of the post data, without breaking its contents?

Upvotes: 0

Views: 38

Answers (1)

Ele
Ele

Reputation: 33726

Have you used readAsDataURL(file) method?

Documentation:

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a URL representing the file's data as a base64 encoded string.

With data base64 encoded you can send it and decode the data in backend.

Hope this helps!

Upvotes: 1

Related Questions