Upload file with AJAX

I would like to know if there is any simple way to perform a file upload via AJAX + JSON.

If there is, what would it be?

Author: brasofilo, 2014-03-18

4 answers

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

However, the formatting of the submission will not be a JSON, but rather in 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 these give.

  • 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 the form values intact, necessary for File upload;
  • text / plain : only spaces are converted to"+";

These being possibilities, what is being trafficked is not a JSON when we are going to communicate by sending data to the server. This data is serialized to be delivered within the date area of the method you are using to traffic 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

<form id="formulario" method="post" enctype="multipart/form-data">
    <input type="text" name="campo1" value="hello" />
    <input type="text" name="campo2" value="world" />
    <input name="arquivo" type="file" />
    <button>Enviar</button>
</form>

Javascript

$("#formulario").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) { // Avalia se tem suporte a propriedade upload
                myXhr.upload.addEventListener('progress', function() {
                    /* faz alguma coisa durante o progresso do upload */
                }, false);
            }
            return myXhr;
        }
    });
});
 74
Author: Gabriel Gartz, 2018-09-26 13:35:20

Simple client-side implementation:

HTML:

<input type="file" id="fileUpload" name="fileUpload" />
<input type="button" id="btnEnviar" value="Enviar" />

Javascript

$(function () {

    var form;
    $('#fileUpload').change(function (event) {
        form = new FormData();
        form.append('fileUpload', event.target.files[0]); // para apenas 1 arquivo
        //var name = event.target.files[0].content.name; // para capturar o nome do arquivo com sua extenção
    });

    $('#btnEnviar').click(function () {
        $.ajax({
            url: 'URL SERVER', // Url do lado server que vai receber o arquivo
            data: form,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function (data) {
                // utilizar o retorno
            }
        });
    });
});

I suggest you search for more complete tutorials on the internet. Search for "file upload ajax" that google will bombard you with several articles, with simple and complex implementations.

 34
Author: Wanattichiã Diogo Stezoucoski, 2014-03-18 19:07:52

I use a generic form on most of the pages I use, both in forms with file uploads and forms without file uploads.

$(form).on('submit', function () {
    var data;
    var contentType = "application/x-www-form-urlencoded";
    var processData = true;
    if ($(this).attr('enctype') == 'multipart/form-data') {
        data = new FormData($('.form-horizontal').get(0));//seleciona classe form-horizontal adicionada na tag form do html
        contentType = false;
        processData = false;
    } else {
        data = $(this).serialize();
    }
    $.ajax({
        data: data,
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        contentType: contentType,
        processData: processData,
        success: function (response) {
            //seu código após sucesso
        },
        error: function (exr, sender) {
                alert('Erro ao carregar pagina');
        }
    });
}
 8
Author: Jozimar Back, 2016-02-05 12:45:23

A simple solution to upload multiple files using Ajax:

HTML:

<input type="file"  id="uploadArquivos" multiple>

JAVASCRIPT-AJAX:

var uploadArquivo = $("#uploadArquivos");

uploadArquivo.on('change', function(e) {
  files = e.target.files;
  var formData = new FormData(),
    file = [];

  $.each(files, function(key, val) {
    file[key] = val;
  });

  formData.append('file', file);

  $.ajax({
    url: 'urlDoArquivo',
    cache: false,
    contentType: false,
    processData: false,
    data: formData,
    type: 'post',
    success: function(data) {

    }
  });

});

When the user selects the files it will create a formData by entering each file and its details and sending to the Ajax url file, if it is in php you can take this value and move to a folder like this:

PHP:

foreach ($_FILES as $value):
   move_uploaded_file($value['tmp_name'], '../temp/' . $value['name']);
endforeach;
 7
Author: Gabriel Rodrigues, 2016-02-05 11:57:50