0

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

它非常适合上传文件,但我有兴趣随文件一起发送其他数据(例如上传文件的人的用户名。

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

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

(假设<input type=file/>HTML 表单中的标准带有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);

});
4

1 回答 1

-2

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

简单地说,“数据”有一个“选项”属性,其中包含将发送到服务器的所有内容。当使用 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 作为我的网络服务器,这意味着附加数据在 app.post 的响应的“参数”属性中可用req.param('username')

IE,

app.post('/file_upload', function(req, res) {

    //see if we got the username
    console.log('name = '+ req.param('username'));
    //Jarrod Dixon
});

希望这有助于节省其他人无结果的搜索时间!

于 2013-08-22T22:01:49.733 回答