Spring MVC 多部分文件上传使用 ajax.我使用弹簧安全性,所以我也添加了 csrf 令牌。我收到以下错误:org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported WARNING: Request method 'POST' not supported
输入表格 jsp:
<form id="fileUploadForm" enctype="multipart/form-data" method="POST">
<input name="id" type="hidden" id="id" value="55" />
<input type="file" class="custom-file-input" id="photo" name="photo" aria-
describedby="photoAddon">
<input type="file" class="custom-file-input" id="sign" name="sign" aria-
describedby="signAddon">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<button type="button" class="btn btn-success"
onclick="profWrapper.uploadPhotoSign()">Upload</button>
</form>
阿贾克斯代码:
uploadPhotoSign : function() {
event.preventDefault();
// Get form
var form = $('#fileUploadForm')[0];
// Create an FormData object
var formData = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "uploadPhotoSign",
data: formData,
processData: false, // prevent jQuery form transforming the data into a query string
contentType: false,
cache: false,
timeout: 600000,
succecc: function(data) {
console.log(data);
},
error: function(e) {
console.log(e.responseText);
}
});
}
控制器:
@PostMapping("uploadPhotoSign")
public ResponseEntity<String> savePhotoSign(HttpServletRequest request,
@RequestParam MultipartFile photo,
@RequestParam MultipartFile sign,
@RequestParam("id") int id){
您可能需要在 ajax 调用中添加 csrf 标头 headers:{ 'X-CSRF-TOKEN': value}
在此处查看多部分项目 但这只是示例项目
即使表单中有csrf隐藏的输入字段,在请求标头中添加csrf令牌对我有用,如下所示:
输入字段:
<input type="hidden" name="${_csrf.parameterName}" id="csrfTkn" value="${_csrf.token}" />
阿贾克斯代码:
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "uploadPhotoSign",
data: formData,
processData: false,
contentType: false,
headers: {'X-CSRF-Token': $('#csrfTkn').val()},
success: function(data) {
console.log(data);
}
});