我想将文件从 Angular 上传到 Spring。我试过这个:
@PostMapping(path = "/upload", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> uploadData(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws Exception {
......
return new ResponseEntity<>(originalName, HttpStatus.OK);
}
Angular 代码:
const formData = new FormData();
formData.append('file', file, file.name);
return this.http.post(environment.api.urls.merchants.uploadLogo, formData);
但是我收到错误:
message: "Unexpected token S in JSON at position 0"
stack: "SyntaxError: Unexpected token S in JSON at position 0↵ at JSON.parse (<
我认为 Spring 必须返回 JSON 响应,但由于某种原因它不起作用。
你知道我如何正确配置 Spring 端点吗?
编辑我尝试过:
@PostMapping(path = "/upload", produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> uploadData(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws Exception {
......
return new ResponseEntity<>(originalName, HttpStatus.OK);
}
最佳答案
您的端点应该生成“text/plain”,因为您返回的是 String 而不是 json 对象。另一方面,Angular 需要 json,因此您会收到此类消息。
如果您想返回 json,请围绕该字符串消息创建包装器。
编辑: 请看一下这个示例 Spring MVC - How to return simple String as JSON in Rest Controller
关于java - Spring 响应中 JSON 中位置 0 处出现意外标记 S,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57452597/