Upload file with AJAX

70

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

If there is one, what would it be?

    
asked by anonymous 18.03.2014 / 18:55

4 answers

60

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

However, the formatting of the submission will not be a JSON, but in the enctype that you set in your FormData , 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 HEX ANSII representation;
  • multipart / form-data : no character is converted, keeping form values intact, required for file upload;
  • text / plain : only spaces are converted to "+";

These being the possibilities, what is being trafficked is not a JSON when we are going to communicate 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 the 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;
        }
    });
});
    
18.03.2014 / 19:33
31

Simple implementation of the "client" side:

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 look for more complete tutorials on the internet. Search for #

    
18.03.2014 / 19:43
7

I use a generic form on most pages I use, both in file uploaded forms and non-uploaded forms.

$(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');
        }
    });
}
    
05.02.2016 / 13:37
5

A simple solution for uploading 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 he will create a formData by inserting each file and its details and sending it to the ajax url file, if it is in php you can take this value and move it to a folder like this:

PHP:

foreach ($_FILES as $value):
   move_uploaded_file($value['tmp_name'], '../temp/' . $value['name']);
endforeach;
    
05.02.2016 / 12:57