Spring不会完整返回JSON。

huangapple go评论138阅读模式
英文:

Spring doesn't return JSON in full

问题

我正在使用Spring Boot和@PostMapping尝试返回一个包含一个Multipart文件和一些字符串的POJO。当我在Postman中查看时,我只看到Multipart对象的一半。文件大小为3KB。我没有收到任何错误消息。当我返回Multipart变量为空时,JSON中的其他变量显示在响应中,所以它们不是空的。如何返回整个JSON?

public class Foo {
    public MultipartFile dataFile;
    public String project;
    public Boolean extract;
    // ... getter - setter - constructor
}

我这样发送它

```java
@PostMapping
public Foo route(@RequestParam("dataFile") MultipartFile dataFile, ... ) {
    // ...
    return fooObject;
}

响应:

{
    "dataFile": {
        "name": "dataFile",
        "bytes": "MIKCAQYJKoZIhvcNAQcCoIKB8jCCge4CA... (文件的一半)"
    }
}

希望这能帮助您返回完整的JSON数据。

英文:

I am using spring boot and @PostMapping trying to return a POJO that contains 1 Multipart file and some String. When i look at Postman i only see half of the Multipart object. File is 3kb. I don't get any errors. When i return the multipart variable null other variables in JSON are being shown in response so they are not empty. How can i return all of the JSON?

public class foo{
    public MultipartFile dataFile;
    
    public String project;
    
    public Boolean extract;

    ... getter - setter - constructor
}

I send it like

@PostMapping
public foo route(@RequestParam("dataFile") MultipartFile dataFile, ... ) {

 ...
    return fooObject;
}

Response

{
    "dataFile": {
        "name": "dataFile",
        "bytes":"MIKCAQYJKoZIhvcNAQcCoIKB8jCCge4CA... (half of the file)

答案1

得分: 1

正如我所想的,MultipartFile 用于上传对象,而不是下载。正如在 Javadoc 中所述:

代表在多部分请求中接收的上传文件的表示。

这意味着它非常适用于上传,但不适用于下载。

最简单(也是最直接)的方法是将 MultipartFile 更改为 byte[],然后将其发送给客户端。

这是一个示例:

public Foo getFile(MultipartFile multipartFile) {
    byte[] bytes = multipartFile.getBytes();
    return new Foo(bytes, "project");
}
英文:

As I thought, the MultipartFile is used to upload object, not to download it. As stated in the Javadoc:
> A representation of an uploaded file received in a multipart request.

Which means, it is great for upload, but that is not the case for download.

The easiest way (and the most straightforward) would be to change the MultipartFile to a byte[] and send that to the client.

Here is an example:

public Foo getFile(MultipartFile multipartFile) {
    byte[] bytes = multipartFile.getBytes();
    return new Foo(bytes, "project");
}

huangapple
  • 本文由 发表于 2020年8月4日 15:45:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63242289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定