Upload a file with AJAX

Asked

Viewed 86,551 times

82

I wonder if there is any simple way to upload files via AJAX + JSON.

If there is, what would it be?

  • 5

    What language is on the server side? Why JSON? i.e. refer to JSON for a specific function?

  • There is a deleted response suggesting this video tutorial: Upload with jQuery and progress bar

5 answers

77


You can upload files using the method POST but shall include the Formdata with the property enctype defined as multipart/form-data for your files to be sent in the request.

However, sending formatting will not be a JSON, but on enctype that you set in your FormData, that 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-date: no character is converted, keeping the form values intact, needed for file upload;
  • text/Plain: only spaces are converted into "+";

These being the possibilities, what is being trafficked is not a JSON when we 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 presented formats.

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;
        }
    });
});
  • how do you choose the folder where the file will be sent?

  • Very important detail, in the I.E the FormData works only from version 10 onwards

  • Guy worked perfectly on my system, vlw.

  • 1

    @Gabrielgartz as I could use your code to fill in a Progress tag in Submit? <progress id="progress" value="0"></progress>

  • But if Formdata is sent via ajax/javascript, the enctype influences?

  • @Karlzillner the FormData uses the default enctype as multipart/form-data, the code will work without it being set in HTML, as written if Javascript is not active or not supported, the form will still work to upload.

Show 1 more comment

36

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 search for more complete tutorials on the internet. Search for "file upload ajax" that google will bombard you with various articles, with simple and complex implementations.

  • 2

    Man, I love you, namoral kkkk

8

I use a generic form on most pages I use, both in file upload forms and forms without file upload.

$(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');
        }
    });
}

7

A simple multi-file upload solution 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 to a folder like this:

PHP:

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

-3

// Campos extras
var colaborador_id = $(".model_id").val();
var nome_recibo = $("#nome_recibo").val();

//Utilizei o FormData para poder enviar arquivo via ajax p php
var data = new FormData(); 
jQuery.each(jQuery('#recibo')[0].files, function(i, file) {    
     data.append('recibo', file); 
});

// Aqui estou adicionando novos campos além do arquivo no FormData.
data.append('colaborador_id', colaborador_id);
data.append('nome_recibo', nome_recibo);

var formData = new FormData();
formData.append("userfile", $('#recibo').prop('files')[0]);

jQuery.ajax({
    url: '/salvar-recibos-colaborador',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    type: 'POST',

    headers: 
    {
        'X-CSRF-TOKEN': APP.token
    },
}).done(data => 
{
    // Mensagem de sucesso
    createFlashMesseger(data.msg, '#flashMensager', data.success);
    limparFlashMesseger(4000);
}) .error(function()
{
    //Mensagem de erro, caso houver
    createFlashMesseger(msg, '#flashMensager', false);
    limparFlashMesseger(4000);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.