英文:
Parsing MultipartFile data to string in spring
问题
我正在尝试将MultipartFile数据解析为字符串,并在Java Spring Boot中将字符串作为响应返回。有人可以建议正确的方法吗?
**controller.java**
```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的请求体发送,并希望读取文件内容并将其存储为字符串。
<details>
<summary>英文:</summary>
I am trying to parse the MultipartFile data to string and return the string as response in java springboot. Can anyone suggest the right approach for this?
**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"
}
]
}
I am sending file.json in request body as multipart/form-data and I want to read the content of the file and store it as string.
</details>
# 答案1
**得分**: 0
如果你正在使用Spring和Spring Boot,那么你不应该使用错误的注解。Spring不支持`Jax-RS`规范。因此,请将你的注解更改为以下内容:
```java
@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
注解。
英文:
If you are using Spring and Spring Boot, then you are not using the proper annotation. Spring does not support Jax-RS
specification. Therefor, change your annotations for this one:
// @POST
// @Path("/modelInfo")
// @Produces({ "application/json" })
@PostMapping(value = "/modelInfo", produces = MediaType.APPLICATION_JSON_VALUE)
Then, to return an object, you can just return the object in the method:
@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;
}
Note:
- Don't forget to add the annotation
@RequestParam
in your method parameter to get the uploaded file. The namefile
must be the name of the attribute uploaded by your POST request - By default, the HTTP Response is 200 when you don't tell Spring to send something else.
- If you want to override that, annotate your method with
@ResponseStatus
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论