Upload AJAX select multiple files

Asked

Viewed 2,230 times

3

This script below selects to UPLOAD only one file. I did several searches and couldn’t find anything I could implement so I could select multiple files.

<script type="text/javascript" >
    $(function(){
        var btnUpload=$('#upload');
        var status=$('#status');
        new AjaxUpload(btnUpload, {
            // Arquivo que fará o upload
            action: 'upload-file.php',
            //Nome da caixa de entrada do arquivo
            name: 'uploadfile',
            onSubmit: function(file, ext){
                 if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){ 
                    // verificar a extensão de arquivo válido
                    status.text('Somente JPG, PNG ou GIF são permitidas');
                    return false;
                }
                status.text('Enviando...');
            },
            onComplete: function(file, response){
                //Limpamos o status
                status.text('');
                //Adicionar arquivo carregado na lista
                if(response==="success"){
                    $('<li></li>').appendTo('#files').html('<img src="./uploads/'+file+'" alt="" /><br />'+file).addClass('success');
                } else{
                    $('<li></li>').appendTo('#files').text(file).addClass('error');
                }
            }
        });

    });
</script>

Does anyone know how to help me in this matter?

  • That one btnUpload=$('#upload') is the form’s Submit button?

  • yes, that’s right!

  • The input file you have there?

  • So I know the implementation should be in this section: new Ajaxupload(btnUpload, { // File that will upload action: 'upload-file.php', //File input box name name: 'uploadfile', Multiple: 'true', I tried to put the option: Multiple: 'true'. But without success!

  • Look at this plugin:, may be well complete and can advance your work.

1 answer

4

To upload multiple files you need to take into account some aspects.

  • you have an input multiple for all different files or inputs for each file?
  • want to upload in series or competitor (sequential)?

Multiple inputs, 1 file per input

In case they are multiple files but each with its input then it’s simple, and all you have to do is create a loop in your code.

competing shipments:

var inputs = $('.inputs');
var status = $('#status');
inputs.get().forEach(function(input, i) {
    // aqui podes usar o "i" se só quiseres saber o numero
    // eu vou usar o nome do ficheiro
    var ficheiro = input.files[0];
    $.ajax({
        url: 'upload-file.php',
        contentType: false,
        processData: false,
        data: (new FormData()).append('file', ficheiro),

https://jsfiddle.net/6pj5ckra/4/

In this case it triggers immediate parallel orders (competitors). It is the fastest way.

serial submissions, consecutive submissions::

var inputs = $('.inputs').get();
var status = $('#status');

function proximoAjax() {
    var proximo = inputs.shift();
    var data = (new FormData()).append('file', proximo.files[0])
    $.ajax({
        url: 'upload-file.php',
        contentType: false,
        processData: false,
        data: data,
        beforeSend: function(file, ext) {
            // etc...
        },
        success: function(file, response) {
            proximoAjax(); // <----
            // etc...
        }
    });
}
proximoAjax();

https://jsfiddle.net/dq8Ldohr/5/

Unique input with attribute multiple, n input files

competing shipments:

var input = $('#input');
var status = $('#status');
var ficheiros = input.get().map(function(input, i) {
    returninput.files[i];
});
ficheiros.forEach(function(ficheiro) {

    $.ajax({
        url: 'upload-file.php',
        contentType: false,
        processData: false,
        data: (new FormData()).append('file', ficheiro),

https://jsfiddle.net/6pj5ckra/3/

serial submissions, consecutive submissions:

var input = $('#input');
var status = $('#status');
var ficheiros = input.get().map(function(input, i) {
    returninput.files[i];
});
function proximoAjax() {
    var proximo = ficheiros.shift();
    var data = (new FormData()).append('file', proximo)
    $.ajax({
        url: 'upload-file.php',
        contentType: false,
        processData: false,
        data: data,
        beforeSend: function(file, ext) {
            // etc...
        },
        success: function(file, response) {
            proximoAjax(); // <----
            // etc...
        }
    });
}
proximoAjax();

https://jsfiddle.net/dq8Ldohr/4/


Notes:

#1

This answer points out the differences and possibilities. I didn’t exactly test your code because I don’t have access to it. This way, using the $.ajax jQuery and not your abstraction new AjaxUpload() I think it also becomes easier to maintain, and useful to others who like me do not know what this new AjaxUpload() ago.

#2

When I use the .get() is to convert a jQuery object into a Array native. Easier to work and know how to use the result in my view.

#3

The main difference in a simple input <input type="file" /> and an input that accepts multiple files <input type="file" multiple /> is (in addition to the attribute multiple) that property .files element names are saved. That is, a simple input only has .files[0] while an input multiple have .files[0], .files[1], etc....

  • I believe that one option to perform a single upload is to have all the input[type='file'] within a form#formID and use var formID = document.getElementById('formID'); new FormData(formID)... in the most the $.ajax uses contenttype by default application/x-www-form-urlencoded while to submit a Formdata the content type must be the multipart/form-data, then I believe you should set processData: false and contentType: false, in the options of $.ajax... in addition your answer deserves a +2.

  • @Tobymosque thank you, I joined processData and contentType in the object passed to ajax.

  • @Sergio implemented the third https://jsfiddle.net/6pj5ckra/3/ code you posted but it didn’t work. Could you implement it in the code I have above? Because for sure I did this implementation wrong.

  • @Gladisonneuzaperosini because there is wrong logic there. You want to send the files when? there is a send button or as soon as files are selected?

  • @Sergio currently my code works when the file is selected. Since the code selects only one for each submission. I would like to keep this style. Just implement so I can select and send several at once.

  • @Sergio has to guide me in this implementation?

  • @Gladisonneuzaperosini so you want to run the ajax when there is the event change of that input for example?

  • @Sergio yes, that.

Show 3 more comments

Browser other questions tagged

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