jQuery文件上传formData不更新

时间:2013-11-19 18:30:41

标签: jquery jquery-file-upload multi-upload

我已经阅读了How to submit additional form data,它确实有效。但我想要完成的是每次发送一个块时更新formData,所以新数据与块一起发送到服务器。

这就是我的尝试:

$('#upload').fileupload({
    maxChunkSize: 100000, // 100KB
    formData: {UploadID: 'just testing'},
}).bind('fileuploadchunkdone', function (e, data) {
    UId = data.jqXHR.responseJSON.files[0].UploadId;
    console.log(UId); // Confirmed, it does have the data sent back by the server
    data.formData = {UploadID: UId}; // It updates, but doesn't send the new data
}).bind('fileuploadchunksend', function (e, data) {
    // tried the same here, but no luck
});

使用Firebug我可以看到发送到服务器的数据。第一个块正确发送formData,但第二个块再次发送相同的数据。

我也尝试过作者所描述的here,但覆盖send处理程序不起作用,因为它只发生在第一个块上。

知道如何实现这个目标吗?

2 个答案:

答案 0 :(得分:1)

尚未对此进行测试,但您可以在更大的范围内定义UId变量,并在每次调用时更新它:

var UId = 'just testing';  

$('#upload').fileupload({
    maxChunkSize: 100000, // 100KB
    formData: function(){
        return [{UploadID: UId}];
    }
}).bind('fileuploadchunkdone', function (e, data) {
    UId = data.jqXHR.responseJSON.files[0].UploadId;
});

答案 1 :(得分:0)

不确定这是否是实现此目的的正确方法。但这就是我所做的:

var UId = 'just testing'; 

$('#upload').fileupload({
    maxChunkSize: 100000, // 100KB
    //formData: {UploadID: UId} REMOVED      
}).bind('fileuploadchunkdone', function (e, data) {
    // UId is set after the chunk is done
    UId = data.jqXHR.responseJSON.files[0].UploadId;
}).bind('fileuploadchunksend', function (e, data) {
    // and append UploadId
    // Yes, append, not override
    data.data.append('UploadId', UId);
    // This will also be fired on the first chunk upload
    // so it is better to set UId in a greater scope as koala_dev said
}

正如我所说,我不知道这是否正确。但它奏效了。

请注意,我已从初始设置中删除formData: {UploadID: UId}。保持它会使每个块发送UploadID两次,首先在块的顶部(在文件数据之前)具有不可更改的值,然后在块的底部(在文件数据之后)与新的值。