我试图用一个表单数据发出post请求,其中包含一个文件和一个Json对象。
要执行此操作,我设置
内容类型
到
未定义
,根据以下帖子
https://stackoverflow.com/a/25183266/4573767
这会导致浏览器将内容类型设置为多部分/表单数据
并正确填充边界。
但是,在(springboot)服务器端,我收到以下错误消息:
已解决由处理程序执行导致的异常:
组织。springframework。网状物HttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException):
无效的
mime类型“未定义”:不包含“/”
因此,浏览器似乎没有正确管理“未定义”的内容类型。
以下是客户端的fetch命令:
// My document blob
var documentBlob = new Blob([JSON.stringify({ documentName: "toto" })], {
type: "application/json"
});
// My Form data containing a file and the document blob
var formData = new FormData();
formData.append("file", this.state.file);
formData.append("document", documentBlob);
// Fetch command
fetch("/document/", {
method: "POST",
headers: {
"Content-Type": undefined
},
data: formData
}).then(function(response) {
console.log("response!");
});
这是服务器端(spring boot rest控制器):
@RestController
@RequestMapping("/document")
public class DocumentController {
@Autowired
private DocumentRepository documentRepository;
@RequestMapping(value = "/", method = RequestMethod.POST, consumes = { "multipart/form-data" })
public boolean addDocument(@RequestPart("document") Document document, @RequestPart("file") MultipartFile file) {
documentRepository.save(document);
return true;
}
}
“文档”是一个简单的pojo:
@Entity
public class Document {
private String documentName;
public Document() {
}
public Document(String documentName) {
this.setDocumentName(documentName);
}
public String getDocumentName() {
return documentName;
}
public void setDocumentName(String documentName) {
this.documentName = documentName;
}
}
所以,我真的不知道问题是在客户端还是服务器端。
谢谢
//////////////////////////////
编辑:
我终于成功了,但是
使用axios代替fecth
:
这是我的finaly spring boot rest控制器:
@RequestMapping(value = "/", method = RequestMethod.POST)
public boolean addDocument(@RequestPart("document") Document document, @RequestPart("file") MultipartFile file) {
// Do things!
return true;
}
以及我的javascript/axios调用:
var documentBlob = new Blob([JSON.stringify({ documentName: "test" })], {
type: "application/json"
});
var formData = new FormData();
formData.append("document", documentBlob);
formData.append("file", this.state.file);
axios({
method: "post",
url: "/document/",
data: formData,
config: { headers: { "Content-Type": "multipart/form-data" } }
})
.then(response => {
console.log("it's working!");
console.log(response);
})
.catch(function(error) {
console.log(error);
});