zoukankan      html  css  js  c++  java
  • RestTemplate将字符串以文件的方式上传

    背景

    在java后台将内容拼接为字符串,然后使用RestTemplate将字符串以文件的方式上传到指定接口

    思路

    使用 RestTemplate 时,将字符串封装为字节流,然后上传

    代码

    /**
         *  将字符串以文件的方式上传
         *
         * @param url 上传的接口 url
         * @param content 上传的字符串内容
         * @param fileName 文件的名称
         * @param toPath 存放在服务器上的位置
         * @return  RestTemplate 的请求结果
         * @author daleyzou
         */
        public static ResponseEntity<String> postFileData(String url, String content,String fileName, String toPath) {
            RestTemplate client = new RestTemplate();
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            param.add("name", fileName);
            param.add("filename", fileName);
            param.add("path", toPath);
            // 构建字节流数组
            ByteArrayResource resource = new ByteArrayResource(content.getBytes()) {
                @Override
                public String getFilename() {
                    // 文件名
                    return fileName;
                }
            };
            param.add("file", resource);
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param,headers);
            return client.exchange(url,HttpMethod.POST, httpEntity, String.class);
        }
    
  • 相关阅读:
    atom那些事儿
    浙江省和杭州市
    Web API之indexedDB和Web SQL
    绝对定位元素居中
    多列等高布局
    git生成ssh key及github ssh key对接
    vuejs模板使用方法
    css3动画图片波纹效果
    sticky footer布局,定位底部footer
    css3圆环闪烁动画
  • 原文地址:https://www.cnblogs.com/daleyzou/p/restTemplateToUploadFile.html
Copyright © 2011-2022 走看看