2013-08-22 29 views
0

我使用Malsup的jQuery Form Plugin異步上傳文件,as per this question如何在使用jQuery Form Plugin上傳文件時提交其他數據?

它的偉大工程的上傳文件,但我感興趣的文件一起發送的附加數據(比如上傳它的人的用戶名。

是否有某種方式來添加這個額外的數據?

下面是當前的代碼,上傳文件的工作原理:

(假設與id=upload HTML表單標準<input type=file/>

// 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); 

}); 

回答

-2

玩了幾天後,我找到了答案。

簡而言之,「數據」有一個'選項'屬性,其中包含將發送到服務器的所有內容。當使用表單設置爲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的迴應的「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 
}); 

希望這有助於挽救別人徒勞的時間尋找的!

相關問題