JQuery文件上传在单个发布请求中发送每个文件? [英] JQuery File Upload sends each file in individual Post Request?

查看:301
本文介绍了JQuery文件上传在单个发布请求中发送每个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是简单而复杂的同时:

我尝试使用jQuery fileUpload库上传文件与春天mvc控制器作为服务器端,但我的文件正在上传每个请求一个。我已经尝试了 singleFileUploads:false 选项,但它不工作,如果我传递4个文件上传时,负责处理帖子的方法被称为4次。

使用这个表单来发布文件:

 < div class =upload-file-div> 
< b>选择要加载的CSV文件< / b> < input id =csvUploadtype =file
name =files []data-url =adminpanel / uploadCsvmultiple />
< / div>
< div id =dropzoneCsv>或者在这里放置文件< / div>

< div id =progressCsv>
< div class =barstyle =width:0%;>< / div>
< / div>

Jquery上传文件的方法:

<$ p fileupload(
{
singleFileUploads:false,
dataType:'json',
done:function( e,data){
$(tr:has(td))。remove();
$ .each(data.result,function(index,file){

$(#uploaded-csv)。append(
$('< tr />')。append(
$('< td />')。text file.fileName))
.append(
$('< td />').text(
file.fileSize))
.append(
$('< td />')。text(
file.fileType))
.append(
$('< td />')。text(
file.existsOnServer ))
.append($('< td />')));
});
$
$ b progressall:function(e,data){
var progress = parseInt(data.loaded / data.total * 100,
10);
$('#progressCsv .bar')。css('width',progress +'%');
},

dropZone:$('#dropzoneCsv')
});



和处理程序方法:

  @RequestMapping(value =/ adminpanel / uploadCsv,method = RequestMethod.POST)
public @ResponseBody
List< FileMeta> uploadCsv(MultipartHttpServletRequest请求,HttpServletResponse响应){

// 1.构建一个迭代器
Iterator< String> itr = request.getFileNames();
MultipartFile mpf = null;
列表< FileMeta> csvFiles = new ArrayList< FileMeta>();
// 2.获取每个文件
while(itr.hasNext()){

// 2.1 get next MultipartFile
mpf = request.getFile(itr。下一个());
System.out.println(mpf.getOriginalFilename()+uploaded!);

// 2.3创建新的fileMeta
FileMeta fileMeta = new FileMeta();
fileMeta.setFileName(mpf.getOriginalFilename());
fileMeta.setFileSize(mpf.getSize()/ 1024 +Kb);
fileMeta.setFileType(mpf.getContentType());

try {
File dir = new File(Thread.currentThread()。getContextClassLoader()
.getResource()。getPath()+CSV);
if(!dir.exists())dir.mkdirs();
File newCSV = new File(dir +\\+ mpf.getOriginalFilename());
if(!newCSV.exists())
{
mpf.transferTo(newCSV);
fileMeta.setExistsOnServer(false);
}
else fileMeta.setExistsOnServer(true);
} catch(IllegalStateException e1){
// TODO自动生成的catch块
e1.printStackTrace();
} catch(IOException e1){
// TODO自动生成的catch块
e1.printStackTrace();
}

// 2.4添加到文件
csvFiles.add(fileMeta);
}

返回csvFiles;



$ b $ p
$ b我真的需要在这里协助:(文件应该加载在一个请求,这就是为什么即时通讯迭代器,但它只是不工作。
$ b

ps。对不起我可怕的英语:($ / / b $ b

解决方案

您可能要尝试程序化文件上传 send 方法将确保只发出一个请求。



基本上保存一个 filelist 变量,每更新一次 fileuploadadd callback,然后使用 filelist 用于 send 方法。 例如:


$ b $

  $ document.ready(function(){
var filelist = [];
$('#form') 。(fileuploadadd,function(e,data){
for(va).fileupload({
... // your fileupload options
) r i = 0; i < data.files.length; (函数()函数){
filelist.push(data.files [i])
}
})

$('#button' {
$('#form')。fileupload('send',{files:filelist});
})

})
$ b $

它的灵感来自于这个问题

我发现它很有用的原因是即使您设置 singleFileUploads false code>,如果你做了多个单独的选择,他们仍然会被发送每个请求,如作者自己在此GitHub问题


My problem is simple and complex same time:

Im tryin to upload files using jQuery fileUpload library with spring mvc controller as server side, but my files are being uploaded by one request each. What i want is posting them ALL in ONE request.

I have tried singleFileUploads: false option but its not working, if i pass 4 files to upload, the method responsible for handling the post is called 4 times.

Im using this form to post files:

<div class="upload-file-div">
    <b>Choose csv files to load</b> <input id="csvUpload" type="file"
    name="files[] "data-url="adminpanel/uploadCsv" multiple />
</div>
<div id="dropzoneCsv">Or drop files here</div>

<div id="progressCsv">
<div class="bar" style="width: 0%;"></div>
</div>

Jquery method to upload files:

$('#csvUpload').fileupload(
                {
                    singleFileUploads: false,
                    dataType : 'json',
                    done : function(e, data) {
                        $("tr:has(td)").remove();
                        $.each(data.result, function(index, file) {

                            $("#uploaded-csv").append(
                                    $('<tr/>').append(
                                            $('<td/>').text(file.fileName))
                                            .append(
                                                    $('<td/>').text(
                                                            file.fileSize))
                                            .append(
                                                    $('<td/>').text(
                                                            file.fileType))
                                            .append(
                                                    $('<td/>').text(
                                                            file.existsOnServer))
                                            .append($('<td/>')));
                        });
                    },

                    progressall : function(e, data) {
                        var progress = parseInt(data.loaded / data.total * 100,
                                10);
                        $('#progressCsv .bar').css('width', progress + '%');
                    },

                    dropZone : $('#dropzoneCsv')
                });

And handler method :

@RequestMapping(value = "/adminpanel/uploadCsv", method = RequestMethod.POST)
    public @ResponseBody
    List<FileMeta> uploadCsv(MultipartHttpServletRequest request, HttpServletResponse response) {

        // 1. build an iterator
        Iterator<String> itr = request.getFileNames();
        MultipartFile mpf = null;
        List<FileMeta> csvFiles = new ArrayList<FileMeta>();
        // 2. get each file
        while (itr.hasNext()) {

            // 2.1 get next MultipartFile
            mpf = request.getFile(itr.next());
            System.out.println(mpf.getOriginalFilename() + " uploaded! ");

            // 2.3 create new fileMeta
            FileMeta fileMeta = new FileMeta();
            fileMeta.setFileName(mpf.getOriginalFilename());
            fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
            fileMeta.setFileType(mpf.getContentType());

            try {
                File dir = new File(Thread.currentThread().getContextClassLoader()
                        .getResource("").getPath()+"CSV");
                if(!dir.exists()) dir.mkdirs();
                File newCSV = new File(dir+"\\"+ mpf.getOriginalFilename());
                if(!newCSV.exists())
                {
                    mpf.transferTo(newCSV);
                    fileMeta.setExistsOnServer(false);
                }
                else fileMeta.setExistsOnServer(true);
            } catch (IllegalStateException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            // 2.4 add to files
            csvFiles.add(fileMeta);
        }

        return csvFiles;
    }

I would really need an assistance here :( Files should be loaded in one request, thats why im doing the iterator, but its just not working.

ps. Sorry for my terrible english :(

解决方案

You may want to try Programmatic file upload instead. The send method will ensure only one request is issued.

Basically keep a filelist variable, update it everytime fileuploadadd callback happens, then use this filelist for the send method.

For example:

$document.ready(function(){
    var filelist = [];
    $('#form').fileupload({
    ... // your fileupload options
    }).on("fileuploadadd", function(e, data){
        for(var i = 0; i < data.files.length; i++){
            filelist.push(data.files[i])
        }
    })

    $('#button').click(function(){
        $('#form').fileupload('send', {files:filelist});
    })

})

It is inspired by this question.

The reason I found it useful is even if you set singleFileUploads to false, if you do multiple individual selections, they will still be sent with individual requests each, as the author said himself in this GitHub issue

这篇关于JQuery文件上传在单个发布请求中发送每个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆