【发布时间】:2013-08-16 06:07:57
【问题描述】:
我正在尝试使用输入类型文件和带有文本的普通输入类型发布 jquery ajax 并使用 request.getParameter("element_name") 从我的 servlet 中检索它们但是尽管在使用 Chrome 检查器时我看到 FormData 的对象我正在发送包含我的文件和我的文本值,servlet 出于某种原因将参数读取为null。
这是我的表单:(ticket_id 正在从另一个 jsp 成功返回)
<form id="upload-form" action="upload" enctype="multipart/form-data" method="post">
<input id="attach-btn" type="file" name="uploadedFile" style="display:none"/>
<input id="tick-id-upload" type="hidden" name="ID" value="<%=ticket_id%>" />
<input id="submit-form" type="button" style="display:none"/>
</form>
这是 jquery ajax post call:
// use to refresh section on submit of a form
$(document).on('click', '#submit-form', function()
{
var form_data = null;
if (drop === false)
{
// form data object with ticket id and file
form_data = new FormData($('#upload-form')[0]);
}
else
{
// append dropped file and value of id seperately
form_data = new FormData();
form_data.append('ID', $('#tick-id-upload').val());
form_data.append('uploadedFile', dropped_files);
}
$.ajax(
{
url: $('#upload-form').attr('action'),
type: 'POST',
async: true,
xhr: function() // custom XMLHttpRequest
{
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload)
{ // check if upload property exists
myXhr.upload.addEventListener('progress', show_progress, false); // for handling the progress of the upload
}
return myXhr;
},
dataType: 'html', // the data type to be returned
success: function(response, status, xhr)
{
$('#progressbar').hide();
if (xhr.getResponseHeader('duplicate') === 'true')
{
// file is duplicate.. display dialog box
setTimeout(function()
{
$('#trigger-dialog').trigger('click');
}, 10);
}
else
{
// replace attachments section by section in response
$('#attachments').html($(response).find('#attachments').html());
execute_attach_datatable();
switch_to_view();
init_progress_bar();
override_section_height();
}
},
error: function(xhr, status, error)
{
alert(xhr.responseText);
},
data: form_data , // what data to pass
cache: false,
contentType: false, // type of data to be sent
processData: false
});
});
这就是我在 servlet 的 doPost 方法中所做的:
int ticket_id = Integer.parseInt(request.getParameter("ID"));
此行返回 NullPointerException,尽管从 Chrome 的“网络”部分可以看到数据正在发送。
请注意,我在不发送输入类型文本的情况下上传文件没有问题。即当我有相同的表单没有tick-id-upload 元素,并使用相同的jquery ajax 调用时,文件上传成功。
对正在发生的事情有任何想法吗?非常感谢!
【问题讨论】: