Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

javascript - Uploading multiple files asynchronously by blueimp jquery-fileupload

I'm using jQuery File Upload library (http://github.com/blueimp/jQuery-File-Upload), and I've been stuck figuring out how to use the library satisfying the following conditions.

  • The page has multiple file input fields surrounded by a form tag.
  • Users can attach multiple files to each input field
  • All files are sent to a server when the button is clicked, not when files are attached to the input fields.
  • Upload is done asynchronously
  • Say the page has 3 input fields with their name attributes being "file1[]", "file2[]" and "file3[]", the request payload should be like {file1: [ array of files on file1[] ], file2: [ array of files on file2[] ], ...}

Here's jsFiddle, it's behaving weird so far in that it sends post request twice and the first one is cancelled.

Updates

Now thanks to @CBroe 's comment, the issue that request is sent twice is fixed. However the keys of request parameter is not correctly set. Here's updated jsFiddle.

http://jsfiddle.net/BAQtG/27/


The core part of js code looks like this.

$(document).ready(function(){
    var filesList = []
    var elem = $("form")
    file_upload = elem.fileupload({
        formData:{extra:1},
        autoUpload: false,
        fileInput: $("input:file"),
    }).on("fileuploadadd", function(e, data){
        filesList.push(data.files[0])
    });

    $("button").click(function(){
        file_upload.fileupload('send', {files:filesList} )
    })

})

Anybody have idea how to get this to work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solved.

Fiddle: http://jsfiddle.net/BAQtG/29/

And js code

$(document).ready(function(){
    var filesList = [],
        paramNames = [],
        elem = $("form");
    file_upload = elem.fileupload({
        formData:{extra:1},
        autoUpload: false,
        fileInput: $("input:file"),
    }).on("fileuploadadd", function(e, data){
        filesList.push(data.files[0]);
        paramNames.push(e.delegatedEvent.target.name);
    });

    $("button").click(function(e){
        e.preventDefault();
        file_upload.fileupload('send', {files:filesList, paramName: paramNames});
    })
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...