【发布时间】:2026-01-09 01:05:01
【问题描述】:
我正在尝试使用包含文件和 Json 对象的表单数据进行发布请求。
为了执行此操作,我将 Content-Type 设置为 undefined,根据以下帖子 https://*.com/a/25183266/4573767
这会导致浏览器将 Content-Type 设置为 multipart/form-data 并正确填充边界。
但是,在(springboot)服务器端,我收到此错误消息:
解决了Handler执行引起的异常: org.springframework.web.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:
这是我最后的 Spring Boot 休息控制器:
@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);
});
【问题讨论】:
标签: javascript spring-boot fetch mime-types form-data