Green Files

Upload file with AJAX + JSON

Day: 06/02/2022 - Time: 09:11:43

You can upload files using the POST method but you must include the FormData with the enctype property set to multipart/form-data for your files to be sent in the request.

However, the formatting of the submission will not be a JSON, but the enctype that you define in your FormData, which depending on the language you are using in the backend will have a different way of interpreting this data.

-Application/x-www-form-urlencoded: is the default enctype, all space values ​​are converted to "+" and non-standard characters are converted to ANSII HEX representation;

-Multipart/form-data: no characters are converted, keeping form values ​​intact, needed for file uploads;

-Text/plain: only spaces are converted to "+";

These being the possibilities, what is being trafficked is not JSON when we are going to communicate by sending data to the server. This data is serialized to be delivered within the data area of ​​the method you are using to travel via HTTP(S) within the formats presented.

During upload you can capture (in modern browsers) upload progress event, as in the example below.

Example using jQuery


<form id="form" method="post" enctype="multipart/form-data"> <input type="text" name="box1" value="hello" /> <input type="text" name="box2" value="world" /> <input name="File" type="file" /> <button>Send</button> </form>


$("#form").submit(function() { var formData = new FormData(this); $.ajax({ url: window.location.pathname, type: 'POST', data: formData, success: function(data) { alert(data) }, cache: false, contentType: false, processData: false, xhr: function() { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // Evaluates whether the upload property is supported myXhr.upload.addEventListener('progress', function() { /* does something during upload progress */ }, false); } return myXhr; } }); });