文件上传inputstream转为multipartfile

摘要:
版本>1.3.3<DiskFileItemfileItem=(DiskFileItem)newDiskFileItemFactory().createItem(“file”;OutputStreamos=fileItem.getOutputStream()){IOUtils.copy(input;

方式一 CommonsMultipartFile

pom

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

test

@Test
public void testOSSServiceImport(){
    File file = new File("test.png");
    DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
            MediaType.ALL_VALUE, true, file.getName());

    try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
        IOUtils.copy(input, os);
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid file: " + e, e);
    }

    MultipartFile multi = new CommonsMultipartFile(fileItem);

}

方式二 mockFile

pom引入spring-test

import org.springframework.mock.web.MockMultipartFile;

MultipartFile file = new MockMultipartFile(name,name, MediaType.MULTIPART_FORM_DATA_VALUE, inputStream);

通过restTemplate调用远程接口,实现文件上传

    private static final String OSS_IMPORT = "/oss/import";
    private static final String OBJECT = "/oss/object";
    private static final String OBJECT_CONTENT = "/oss/object/content";

    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private OssDao ossDao;
    @Autowired
    private RestTemplate restTemplate;

    private static String ossEndpoint;

    @PostConstruct
    private void init() {
        SysConfigPo sysConfigPo = sysConfigDao.findByTypeAndSubTypeAndKey(TYPE, SUB_TYPE, CONFIG_KEY);
        ossEndpoint = Objects.isNull(sysConfigPo) ? null : sysConfigPo.getValue();
    }
    private MultiValueMap<String, Object> toRequestParams(OssServiceQo ossServiceQo, MultipartFile file) {

        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
        parts.add("file", file.getResource());

        Map<String, Object> requestParams = JSONUtils.parseObject(JSONUtils.toJSONString(ossServiceQo));
        if (!CollectionUtils.isEmpty(requestParams)) {
            Set<Map.Entry<String, Object>> entries = requestParams.entrySet();

            for (Map.Entry<String, Object> entry : entries) {
                String key = entry.getKey();
                if (org.springframework.util.StringUtils.isEmpty(entry)) {
                    continue;
                }
                parts.add(key, entry.getValue());
            }
        }
        return parts;
    }

入参为multipartFile

    @Override
    public Response<Album> save(String namespace, String prefix, String name, MultipartFile file) {
        OssServiceQo ossServiceQo = getOssServiceQo(namespace, prefix, name);
        MultiValueMap<String, Object> body = toRequestParams(ossServiceQo, file);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, httpHeaders);
        return restTemplate.exchange(ossEndpoint + OSS_IMPORT, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<Response<Album>>() {
        }).getBody();
    }
    private MultiValueMap<String, Object> toRequestParams(OssServiceQo ossServiceQo, MultipartFile file) {

        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
        parts.add("file", file.getResource());

        Map<String, Object> requestParams = JSONUtils.parseObject(JSONUtils.toJSONString(ossServiceQo));
        if (!CollectionUtils.isEmpty(requestParams)) {
            Set<Map.Entry<String, Object>> entries = requestParams.entrySet();

            for (Map.Entry<String, Object> entry : entries) {
                String key = entry.getKey();
                if (org.springframework.util.StringUtils.isEmpty(entry)) {
                    continue;
                }
                parts.add(key, entry.getValue());
            }
        }
        return parts;
    }

入参为inpurtStream

    @Override
    public Response<Album> save(String namespace, String prefix, String name, InputStream inputStream) {
        OssServiceQo ossServiceQo = getOssServiceQo(namespace, prefix, name);
        MultiValueMap<String, Object> body = toRequestParams(ossServiceQo, inputStream);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, httpHeaders);
        return restTemplate.exchange(ossEndpoint + OSS_IMPORT, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<Response<Album>>() {
        }).getBody();
    }
    private MultiValueMap<String, Object> toRequestParams(OssServiceQo ossServiceQo, InputStream inputStream) {
        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
        Resource resource = new CommonInputStreamResource(inputStream);
        parts.add("file", resource);
        Map<String, Object> requestParams = JSONUtils.parseObject(JSONUtils.toJSONString(ossServiceQo));
        if (!CollectionUtils.isEmpty(requestParams)) {
            Set<Map.Entry<String, Object>> entries = requestParams.entrySet();

            for (Map.Entry<String, Object> entry : entries) {
                String key = entry.getKey();
                if (org.springframework.util.StringUtils.isEmpty(entry)) {
                    continue;
                }
                parts.add(key, entry.getValue());
            }
        }
        return parts;
    }

感谢

通过`RestTemplate`上传文件(InputStreamResource详解)

免责声明:文章转载自《文件上传inputstream转为multipartfile》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇iOS开发:cocoapods的使用浙大版《C语言程序设计(第3版)》题目集 练习2-12 输出华氏-摄氏温度转换表 (15 分)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

React实现组件缓存的一种思路

前言 对于某个页面中的某个组件,很多时候需要其保持一直激活的状态,之前我的博客里面有一篇提到一种缓存策略,就是利用Route的children方法来display该组件或隐藏该组件。但是这种方式需要借助到Route组件并且只能缓存整个页面,而不是页面中的部分组件。并且这种缓存单纯的只是在页面上把它的display变成了block和none,仅仅是在路由离...

Video.js

Video.js 官网: https://videojs.com/ 开源HTML5播放器框架 优点 支持多种格式,可以支持MP4、WebM、HLS、RTSP等。 可以自定义主题样式。 插件丰富。 支持广泛,可支持PC端各种浏览器和移动端的浏览器。 插件列表 https://videojs.com/plugins 使用 原生代码,未使用主题样式 <he...

Qt布局管理

设计软件中各个部件的位置排列,有两种方法: 1.设置widget的在父窗体中的坐标和大小 widget->move(x,y); widget->resize(width,height); //widget->setGeometry(QRect(x,y,width,height)); 什么时候用:不想被布局约束,对这种控件可控制时 例如下面...

pycharm常用配置详解

  PyCharm是一种Python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语法高亮、Project管理、代码跳转、智能提示、自动完成、单元测试、版本控制。此外,该IDE提供了一些高级功能,以用于支持Django框架下的专业Web开发。 Windows版本下载地址:https://www.jetbrains....

SaltStack--远程执行

saltstack远程执行 安装完Saltstack后可以立即执行shell命令,更新软件包并将文件同时分不到所有受管系统。所有回复都以一致的可配置格式返回。远程执行参考文档:http://docs.saltstack.cn/topics/tutorials/modules.html [root@salt-master ~]# salt '*' cmd.r...

ELK华为云的镜像下载地址(ElasticSearch,logstash,kibana)

ElasticSearch: https://mirrors.huaweicloud.com/elasticsearch/?C=N&O=D logstash: https://mirrors.huaweicloud.com/logstash/?C=N&O=D kibana: https://mirrors.huaweicloud.com/k...