{{format('0')}} {{format('448')}} {{format('1112')}}

RestTemplate文件上传请求FileSystemResource被FastJson序列化后变为0kb的问题 [ 技术杂谈 ]

九叶的小窝 文章 正文

As Long As You Love Me.
分享

九叶

{{nature("2022-04-19 13:42:44")}}更新

1. 问题

有个功能需要调用一个传输文件的api,使用FileSystemResource进行传输,在调用api之前使用JSONObject.toJSONString()输出一下log之后 发现每次输出log之后本地文件就会变成0KB

2. 分析

FileSystemResource 是spring封装的类,其实现了WritableResource接口

public class FileSystemResource extends AbstractResource implements WritableResource {...}

在递归解析字段时,由于是采用getter方式,getOutputStream被当做getter方法被调用,

public interface WritableResource extends Resource {
        // omit

    /**
     * Return an {@link OutputStream} for the underlying resource,
     * allowing to (over-)write its content.
     * @throws IOException if the stream could not be opened
     * @see #getInputStream()
     */
    OutputStream getOutputStream() throws IOException;
}

getXX本意是获取XX字段的值,但getOutputStream()被调用,拿到output后未写入任何值,相当于向output写入了空,后被flush到磁盘导致的文件被重写了

3. 解决

  1. 不要toJsonString打印复杂对象,特别是不熟悉的class
  2. 避免使用FileSystemResource类,使用其他对象代替

4. 参考资料

https://github.com/alibaba/fastjson/issues/3436

https://github.com/alibaba/fastjson/issues/3547#issuecomment-728782084

评论 0
0
{{userInfo.data?.nickname}}
{{userInfo.data?.email}}
TOP 2
Minecraft | [1.12.2] 核电工艺模拟器 1.2.25 —— 汉化版

{{nature('2021-12-07 15:29:00')}} {{format('2671')}}人已阅读

TOP 3
SSM搭建Spring单元测试环境

{{nature('2021-01-31 20:01:00')}} {{format('1172')}}人已阅读

TOP 4
dispatcher-servlet.xml文件配置模板

{{nature('2020-12-11 21:17:00')}} {{format('1085')}}人已阅读

TOP 5
Windows平台Nacos启动报错无法创建Bean实例

{{nature('2021-04-22 15:16:00')}} {{format('1057')}}人已阅读

目录

标签云

Java

一言

# {{hitokoto.data.from || '来自'}} #
{{hitokoto.data.hitokoto || '内容'}}
作者:{{hitokoto.data.from_who || '作者'}}
自定义UI
配色方案

侧边栏