最近公司的一個項目涉及到導入Excel的功能,於是就想到用ajaxFileUpload來實現上傳文件,因為用過很多次了,網上也有很多文章介紹。使用方法不表。但是在附帶參數這個環節卡住了:文件可以上傳到后台,但是附帶的json參數怎么都傳不到后台。
通過網上的文章和查看ajaxFileUpload.js源碼發現:ajaxFileUpload.js本身根本就不支持附帶參數。
function ajaxFileUpload(DOMId,row){ var param={"exam.class_id":row.class_id, "exam.subject_id_list":row.subject_id_list, "exam.subject_name_list":row.subject_name_list}; $.ajaxFileUpload({ url:'importExcel_Exam_n.do?'+param, type:'post', secureuri: false, fileElementId: DOMId, dataType:'text/plain', data:param, success: function(data, status){ $('#imageName').html(data); }, error: function(data, status, e){ $('#imageName').html('上傳失敗'); } }); }
data這一個參數根本就不被ajaxFileUpload.js支持。
但是可以通過更改ajaxFileUpload.js來支持這一參數。具體如下:
打開ajaxFileUpload.js源碼(網上的版本好像一般都是未壓縮的,所以可以直接查看源碼),找到這塊代碼:
createUploadForm: function(id, fileElementId){ var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); //...中間省略 return form; }
新增紅色部分代碼:
createUploadForm: function(id, fileElementId,data){ var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); //...中間省略 if(data){ for(var i in data){ $('<input type="hidden" name="'+i+'" value="'+data[i]+'"/>').appendTo(form); } } return form; }
還有一處需要修改,是為了接收data參數:
ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = s.fileElementId; var form = jQuery.createUploadForm(id, s.fileElementId);
新增紅色部分:
ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = s.fileElementId; var form = jQuery.createUploadForm(id, s.fileElementId,s.data);
修改完保存,再次運行,后台就可以接收到傳遞過來的json參數了!
