首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将multipartFile从角发送到Java

将multipartFile从角发送到Java
EN

Stack Overflow用户
提问于 2022-03-16 08:37:09
回答 1查看 364关注 0票数 0

我正在使用Java创建一个API,而我在文件方面也面临着一个问题。

这是我的API定义:

代码语言:javascript
运行
复制
@RequestMapping(value="/createUser", method = RequestMethod.POST)
ResponseEntity<?> fromFile(@RequestBody FileRequest FileRequest);

这个FileRequest输入Bean只有一个项(当我解决问题时),但将来它将有更多的项,如userName或userAge等其他表单数据。

代码语言:javascript
运行
复制
public class FromFileRequest {

  @NotEmpty(message = "Value for input 'file' can't be null" )
  private MultipartFile file;

  public MultipartFile getFile() {
    return file;
  }

  public void setFile(MultipartFile file) {
    this.file = file;
  }
}

在角边:

代码语言:javascript
运行
复制
load(file: File): Observable<any> {
    let formData: FormData = new FormData();    
    formData.append('file', file);
    return this.apiService.post('/api/createFile', formData);
}

我在Java端收到一个错误

代码语言:javascript
运行
复制
09:31:51,010 INFO [stdout] (http-127.0.0.1:8080-4) org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.web.multipart.MultipartFile]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.web.multipart.MultipartFile` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
09:31:51,010 INFO [stdout] (http-127.0.0.1:8080-4) at [Source: (PushbackInputStream); line: 1, column: 9] (through reference chain: com.mypackage.api.dto.FileRequest["file"])
09:31:51,010 INFO [stdout] (http-127.0.0.1:8080-4) at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:242) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
09:31:51,010 INFO [stdout] (http-127.0.0.1:8080-4) at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]

我真的不知道问题是在角度方面还是在Java方面,因为如果我只使用MultipartFile类型作为API中的输入(并正确地修改角),它就能工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-16 08:45:01

您不能使用@RequestBody,您必须使用@RequestPart

代码语言:javascript
运行
复制
@RequestMapping(value="/createUser", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
ResponseEntity<?> fromFile(@RequestPart(value = "file") MultipartFile file)

如果你需要用你的文件发送一个DTO,

  1. 手动将其固定在角侧:

formData.append('dto', JSON.stringify(data));

@RequestPart(value = "dto") String stringDTO)部件上的

  1. 添加另一个

  1. 手动调用对象映射程序:

YourDtoClass dto = objectMapper.readValue(stringDTO, YourDtoClass.class);

objectMapper来自包com.fasterxml.jackson.databind

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71493907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档