有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript当前请求不是多部分请求

我正在尝试向我的服务器发送一个映像。我不断得到错误:当前请求不是一个多部分请求。当我在《邮递员》上测试它时,效果很好

这是我的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 Working

知道我做错了什么吗?提前谢谢


共 (2) 个答案

  1. # 1 楼答案

    您可以尝试修改它-

    var formData = new FormData(document.querySelector("#newImagesForm")[0]);
    
  2. # 2 楼答案

    下面的代码应该可以完成这项工作: 基本上,您可以创建一个新的表单对象并将文件数据附加到其中。 您可以通过添加更多的“data.append”行向其添加多个数据属性

        function uploadPicture() {
            var input = document.querySelector('input[type="file"]')
            console.log(productID);
            var data = new FormData()
            data.append('file', input.files[0])
            fetch('/uploadFile/', {
                method: 'POST',
                body: data
            })
            .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));
        }
    

    HTML:

            <input type="file" name="file" id="fileinput">
            <input type="submit" value="Upload" onclick="uploadPicture()">