我正在尝试将图像发送到我的服务器。我不断收到错误消息:当前请求不是多部分请求。当我在 Postman 中测试它时,它工作正常。
这是我的html表单:
function saveImageToProduct() {
var formData = new FormData(document.querySelector("#newImagesForm"));
var encData = new URLSearchParams(formData.entries());
fetch("/uploadFile", { method: 'POST', body: encData })
.then(response => Promise.all([response.status, response.json()]))
.then(function([status, myJson]) {
if (status == 200) {
console.log("succeed!");
} else {
console.log("failed!");
}
})
.catch(error => console.log(error.message));
return false;
}
<form enctype="multipart/form-data" novalidate="novalidate" id="newImagesForm" method="post">
<div>
<p>Selecteer een afbeelding:</p>
<input id="file" name="file" type="file"/>
</div>
<br>
<div>
<button id="button" onclick="return saveImageToProduct()" class="btn btn-lg btn-info btn-block">
<span>Voeg aanbieding toe</span>
</button>
</div>
</form>
后端Java代码:
@PostMapping("/uploadFile")
public ProductImage uploadFile(@RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/uploads/")
.path(fileName)
.toUriString();
return new ProductImage(fileName, fileDownloadUri,
file.getContentType(), file.getSize());
}
当我尝试发送图像时,我在后端收到 500 错误:
2019-03-10 19:40:33.588 ERROR 5668 --- [io-9001-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request] with root cause org.springframework.web.multipart.MultipartException: Current request is not a multipart request
当我在 Postman 中执行此操作时,它可以正常工作,如下图所示:
胡子哥哥
哈士奇WWW
相关分类