java – 使用输入类型和文件NullPointerException发布FormData对象
|
我正在尝试使用输入类型文件和带有文本的普通输入类型进行 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的帖子: // 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,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调用时,文件上传成功. 对于发生了什么的任何想法?非常感谢! 解决方法您无法使用request.getParameter()直接读取multipart / form请求参数.相反,您需要使用 getPart方法读取多个部分请求的不同部分.以下是迭代多部分请求部分的方法:for (Part part : request.getParts()) {
}
请访问此博客以获取详细示例:http://balusc.blogspot.in/2009/12/uploading-files-in-servlet-30.html (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
