我正在尝试上传一个包含进度条的文件。
var fileInput = document.getElementById('jquery-ajax-single')
var form = new FormData();
form.append('uploadFile',fileInput.files[0]);
$.ajax({
url: "file/upload",
processData : false,
contentType : false,
data : form,
type : 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function(e) {
console.log(Math.floor(e.loaded / e.total *100) + '%');
$('#progress-jquery-ajax-single.progress-bar-progress').css(
'width', Math.floor(e.loaded / e.total * 400)+ 'px'
);
};
return xhr;
}
});
上面的代码正常工作,可以转到FileController
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping(value = "/upload", method = RequestMethod.POST, headers = "X-Requested-With=XMLHttpRequest")
public void upload(@RequestParam MultipartFile uploadFile){
System.out.println("name : " + uploadFile.getOriginalFilename());
System.out.println("content-type : " + uploadFile.getContentType());
System.out.println("size : " + uploadFile.getSize());
}
}
每次处理ajax时都会显示上传进度,达到100%后会进入FileController并打印输入文件信息,但在查看chrome浏览器控制台后会返回:
jquery-2.1.4.js:8630 POST http://localhost:8080/FileUploadWeb/file/upload 404(Not Found)。
我也尝试使用dropzone.js,它也返回错误404,但网址变为http://localhost:8080/FileUploadWeb/file/file/upload
<form id="my-dropzone"action="file/upload" class="dropzone"></form>
答案 0 :(得分:0)
绊倒this之后,应该起作用的技巧是在POST方法中返回一个ResponseBody
实体:
@PostMapping(value = "/upload")
public ResponseEntity<String> upload(@RequestParam MultipartFile uploadFile) {
System.out.println("name : " + uploadFile.getOriginalFilename());
System.out.println("content-type : " + uploadFile.getContentType());
System.out.println("size : " + uploadFile.getSize());
return new ResponseEntity<>("File Uploaded Successfully.", HttpStatus.OK);
}