gpt4 book ai didi

java Spring使用ajax上传文件

转载 作者:行者123 更新时间:2023-11-30 06:04:20 27 4
gpt4 key购买 nike

如何通过ajax发送文件?

我知道如何使用默认表单将文件上传到服务器,我的意思是:

<div class="addBook" >
<form id="add" action="/add" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input name="title" type="text" class="form-control" id="title" placeholder="title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" class="form-control" id="description" rows="3"></textarea>
</div>
<div class="form-group">
<label for="picture">file input</label>
<input name="picture" type="file" class="form-control-file" id="picture">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

以及此代码的 Controller

@RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<String> add(
@RequestParam(value = "title",required = false)String title,
@RequestParam(value = "description",required = false)String description,
@RequestParam(value = "picture",required = false)MultipartFile file){
Book book = new Book();
book.setFileName(addFile(file));
book.setTitle(title);
book.setDescription(description);


return new ResponseEntity<String>("index", HttpStatus.OK);
}
}

这段代码可以工作,但我想用ajax来编写它。我试过这个:

$(document).ready(function () {
$("#add").submit(function (e) {
e.preventDefault();
$.ajax({
url:'/add',
type:'POST',
contentType:"multipart/form-data",
statusCode:{
409:function () {
$("#mess").html('<b>Логин занят</b>');
},
200:function(){
console.log("successfull")
}
}
})
})
})

但是我收到以下错误:

2018-08-03 21:00:29.317 ERROR 9204 --- [nio-8080-exec-3] 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: Failed to parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found] with root cause

我在 Google 中进行了搜索,但没有找到任何解决方案。

最佳答案

您在“$.ajax”调用中没有提交任何“数据”,因此您没有发送任何文件并收到此错误。请参阅相关主题的示例:

Sending multipart/formdata with jQuery.ajax

关于java Spring使用ajax上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51676107/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com