【问题标题】:Parsing MultipartFile data to string in spring在 spring 中将 MultipartFile 数据解析为字符串
【发布时间】:2020-08-04 09:52:21
【问题描述】:

我正在尝试将 MultipartFile 数据解析为字符串并在 java springboot 中将字符串作为响应返回。任何人都可以为此提出正确的方法吗?

controller.java

@POST
@Path("/modelInfo")
@Produces({ "application/json" })
public Response getPretrainedModel(MultipartFile data) throws IOException {
    String content = new String(data.getBytes(), StandardCharsets.UTF_8);
    return Response.status(Response.Status.OK).entity(content).build();
}

file.json

{
  "documents": [
    {
      "id": "1",
      "text": "abc"
    }
  ]
}

我在请求正文中将 file.json 作为 multipart/form-data 发送,我想读取文件的内容并将其存储为字符串。

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    如果您使用的是 Spring 和 Spring Boot,那么您没有使用正确的注解。 Spring 不支持Jax-RS 规范。因此,请更改您的注释:

    //    @POST
    //    @Path("/modelInfo")
    //    @Produces({ "application/json" })
    @PostMapping(value = "/modelInfo", produces = MediaType.APPLICATION_JSON_VALUE)
    

    那么,要返回一个对象,你可以在方法中返回对象:

    @PostMapping(value = "/modelInfo", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getPretrainedModel(@RequestParam("file") MultipartFile data) throws IOException {
        String content = new String(data.getBytes(), StandardCharsets.UTF_8);
        return content;
    }
    

    注意:

    • 不要忘记在你的方法参数中添加注解@RequestParam来获取上传的文件。名称file必须是您的POST请求上传的属性名称
    • 默认情况下,当您不告诉 Spring 发送其他内容时,HTTP 响应为 200。
    • 如果你想覆盖它,用@ResponseStatus注释你的方法

    【讨论】:

    • 感谢您的解决方案。只是想知道除了MultipartFile,还有没有其他方法可以读取request body form-data发送的文件内容?
    猜你喜欢
    • 1970-01-01
    • 2022-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 2017-02-02
    相关资源
    最近更新 更多