我正在尝试将文件从客户端上传到服务器.在此过程中使用SpringMVC和JQuery.单击按钮触发的文件上载过程运行Javascript函数.我总是"TypeError: Cannot read property 'open' of undefined"
从Javascript 获得.
HTTP请求在客户端(浏览器)处停止.
Javascript函数
function fileUploadFunction() { if(!$('#fileupload').val()){ console.log('No File Selected'); $('#fileUploadStatus').val('File Required'); return; } var uploadedFile = $('#fileupload')[0].files[0]; var uploadFileFormData = new FormData(); uploadFileFormData.append('uploadedFile', uploadedFile); $.ajax({ url : 'fileUpload', type : 'POST', //dataType : 'text', //dataType : 'multipart/form-data', //enctype : 'multipart/form-data', processData : false, contentType : false, mimeType: 'multipart/form-data', data : uploadFileFormData, /* data : { uploadedFile : $('#fileupload')[0].files[0] }, */ beforeSend : function() { $('#fileUploadStatus').val(''); }, success : function(reply) { console.log(reply); }, error : function(xhr) { console.log(xhr); }, complete : function(reply) { $('#fileUploadStatus').val(reply); }, xhr : function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentComplete = (evt.loaded / evt.total) * 100; percentComplete = Math.round(percentComplete); console.log(percentComplete); } }, false); } }); }
Spring MVC控制器
@RequestMapping(value = "fileUpload", method = RequestMethod.POST) public @ResponseBody String fileUpload(ModelMap model, HttpServletRequest request, @RequestParam(name = "uploadedFile") MultipartFile uploadedFile) {
当我在浏览器中调试时,我可以看到uploadFileFormData
没有附加.
new FormData();
是不是用纯文本的工作也.
JQuery : jquery-3.1.1.min.js
.
这工作时,我使用的var xhr = new XMLHttpRequest;
,但我需要使用场景,如来处理Ajax请求BeforeSend
,Success
,error
,Complete
...
var xhr = new XMLHttpRequest; xhr.open('POST', 'fileUpload', true); xhr.send(uploadFileFormData);
这里也是uploadFileFormData
空的.
在函数末尾添加一个返回值.如果不这样做,那么请求尝试使用的xhr对象将是未定义的.那应该是你错误的根源.见下面的代码.
xhr : function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentComplete = (evt.loaded / evt.total) * 100; percentComplete = Math.round(percentComplete); console.log(percentComplete); } }, false); return xhr;//add this line. doing so fixed it for me. }