使用jQuery Form插件上传文件时,如何提交额外数据

How can I submit additional data when uploading a file with the jQuery Form Plugin?

本文关键字:何提交 提交 数据 插件 Form jQuery 文件 使用      更新时间:2023-09-26

根据这个问题,我正在使用Malsup的jQuery Form插件异步上传文件。

它非常适合上传文件,但我有兴趣在上传文件的同时发送额外的数据(比如上传者的用户名。

有没有办法添加这些额外的数据?

以下是当前用于上传文件的代码:

(假设HTML形式的标准<input type=file/>具有id=upload

// site/js/app.js
var app = app || {};
(function($){

})(jQuery);
// prepare the form when the DOM is ready 
$(document).ready(function() { 

         var options =
         { 
            url: 'http://localhost:3000/file_upload',
            dataType: 'json',
            success: function(response, statusText, xhr, form) 
            {
                alert('success!');
            }; 
        $("#upload").ajaxForm(options);
});

玩了几天后,我找到了答案。

简单地说,有一个"数据"的"选项"属性,它包含将发送到服务器的所有内容。当使用Form设置为enctype="multipart/form-data"时,这只获取文件类型输入,忽略其他所有内容。

但是,如果您可以访问其他输入字段的值(听起来像是$!的作业),则可以使用特定的回调函数手动添加额外的数据。

这将使您的jQuery代码看起来像这样:

// site/js/app.js
var app = app || {};
(function($){

})(jQuery);
/*
$('#upload').submit(function()
{
    alert('Handler for .submit() called.');
    return false;
})*/
// prepare the form when the DOM is ready 
$(document).ready(function() { 

         var options =
         { 
            url: 'http://localhost:3000/file_upload',
            dataType: 'json',
            beforeSubmit: function(arr, $form, options) 
            {
                //add additional data that is going to be submit
                //for example
                arr.push({ 'name': 'username',
                           'value': 'Jarrod Dixon'});
            }, 

        }; 
        $("#upload").ajaxForm(options);
});

在我的例子中,我使用express.js作为我的Web服务器,这意味着额外的数据在app.post的response的"param"属性req.param('username')中可用。

app.post('/file_upload', function(req, res) {
    //see if we got the username
    console.log('name = '+ req.param('username'));
    //Jarrod Dixon
});

希望这能帮助其他人节省数小时的搜索时间!