将带有一些对象和文件从 ReactJS 发布的 json 发布到 REST Spring 服务器



我正在从我的 ReactJS 应用程序发送帖子 女巫包含一些 json 对象 映射和用户上传的文件。

axios.post(`http://localhost:8080/api/maps`, this.state)

哪里

this.state = {map: {title: "Title", layers: [...] etc.}, files: [file1]}

我从FileReaderInput获取file1,但它与html的输入类型文件中的文件完全相同。此文件具有字段 lastModified, lastModifiedDate, name, size, type, webkitRelativePath, __proto_。

在我的 REST 服务器上,我有这个:

@RequestMapping(value = "/maps", method = RequestMethod.POST)
public @ResponseBody
HttpStatus add(@RequestBody CreateMapWrapper wrapper) throws IOException, InterruptedException {
    System.out.println(wrapper.getMap());
    System.out.println(wrapper.getFiles());
    return HttpStatus.OK;
}

哪里

public class CreateMapWrapper {
    private com.gismaps.pojos.Map map;
    private Set<MultipartFile> files;
    public Map getMap() {
        return map;
    }
    public void setMap(Map map) {
        this.map = map;
    }
    public Set<MultipartFile> getFiles() {
        return files;
    }
    public void setFiles(Set<MultipartFile> files) {
        this.files = files;
    }
}

当我发送我的 Map 对象和空文件数组时,一切正常。请求映射到 CreateMapWrapper 并打印 Map 和空值数组。

但是当我将文件放置到数组时,我得到异常:

WARN 4348 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON document: Can not construct instance of org.springframework.web.multipart.MultipartFile: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: java.io.PushbackInputStream@79e43652; line: 1, column: 577] (through reference chain: com.gismaps.CreateMapWrapper["files"]->java.util.HashSet[1]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of org.springframework.web.multipart.MultipartFile: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: java.io.PushbackInputStream@79e43652; line: 1, column: 577] (through reference chain: com.gismaps.CreateMapWrapper["files"]->java.util.HashSet[1])

怎么了?这是在 REST 中映射的东西,或者我以错误的方式发送文件格式 React?我甚至可以发布这样的东西吗?

我可能正在做一些愚蠢的事情,但我从来没有将文件上传到Spring REST。

看起来不像是反应特定的问题。看起来您没有设置 REST 终结点来处理多部分。你可能想看看这个 spring 教程,看看如何在服务器端处理文件上传:https://spring.io/guides/gs/uploading-files/

在Spring Rest Controller中获取表单数据的简单方法如下:

RequestMapping(value = "/maps", method = RequestMethod.POST)
public @ResponseBody Object uploadFiles(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
    //get form data fields
    final String field= request.getParameter('fieldName');
    //and so on......
    //Now get the files.
    Iterator<String> iterator = request.getFileNames();
    MultipartFile multipartFile = null;
    while (iterator.hasNext()) {
        multipartFile = request.getFile(iterator.next());
    }
}

最新更新