当前请求不是多部分请求

时间:2019-03-10 19:00:10

标签: javascript java html

我正在尝试将图像发送到服务器。我不断收到错误消息:当前请求不是多部分请求。当我在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 Working

知道我在做什么错吗?预先感谢

2 个答案:

答案 0 :(得分:1)

下面的代码可以完成这项工作: 基本上,您将创建一个新的Form对象,并将文件数据附加到该对象。 您可以通过添加更多“ 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()">

答案 1 :(得分:0)

您可以尝试对其进行修改-

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