RestTemplate上传多文件(转存URL文件)

将网络文件链接转成输入流之后上传

    /**
     * 
     * @param list 为网络文件地址
     * @return
     */
public JSONObject uploadFiles(List<String> list) {
        ArrayList<CommonInputStreamResource> commonInputStreamResources = new ArrayList<>();
        list.forEach(e -> {
        //将链接转为InputStreamResource
            commonInputStreamResources.add(urlToInputStream(e));
        });
        return httpUploadFile(commonInputStreamResources);
    }
    /**
     * 将url转换成InputStreamResource
     *
     * @param strUrl
     * @return
     */
    @SneakyThrows
    public CommonInputStreamResource urlToInputStream(String strUrl) {
        URL url = new URL(strUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
        InputStream inputStream = conn.getInputStream();

        CommonInputStreamResource commonInputStreamResource =
                new CommonInputStreamResource(inputStream, inputStream.available(), System.currentTimeMillis()+getFileType(strUrl));
//        int byteread;
//        byte[] buffer = new byte[1024];
//        ArrayList<Byte> bytes = new ArrayList<>();
//
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        while ((byteread = inputStream.read(buffer)) != -1) {
//            baos.write(buffer, 0, byteread);
//        }
//
//        return new ByteArrayResource(new String(baos.toByteArray(), StandardCharsets.UTF_8).getBytes()) {
//            @Override
//            public String getFilename() throws IllegalStateException {
//                return System.currentTimeMillis()+getFileType(strUrl);
//            }
//        };
        return  commonInputStreamResource;
    }
 /**
     * 获取文件后缀名
     * @param filename
     * @return
     */
    public static String getFileType(String filename){
        int pos = filename.lastIndexOf(".");
        if(pos == -1){
            return "";
        }
        return filename.substring(pos-1);
    }
 /**
     * 上传文件
     *
     * @param byteArrayResources
     * @return
     */
    public JSONObject httpUploadFile(List<CommonInputStreamResource> byteArrayResources) {
        RestTemplate restTemplate = new RestTemplate();
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType(MediaType.MULTIPART_FORM_DATA_VALUE);
        headers.setContentType(type);
        //设置请求体,注意是LinkedMultiValueMap
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        byteArrayResources.forEach(e -> {
            form.add("files", e);
        });
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
        JSONObject uploadKey = getUploadKey();
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(projectUploadConfig.getUpfiles())
                .queryParam("appid", uploadKey.getStr("appid"))
                .queryParam("sign", uploadKey.getStr("sign"))
                .queryParam("timestamp", uploadKey.getStr("timestamp"))
                .build();
        URI uri = uriComponents.toUri();
        return restTemplate.postForObject(uri, files, JSONObject.class);
    }
import org.springframework.core.io.InputStreamResource;

import java.io.InputStream;


public class CommonInputStreamResource extends InputStreamResource {
    private long length;
    private String fileName;

    public CommonInputStreamResource(InputStream inputStream, long length, String fileName) {
        super(inputStream);
        this.length = length;
        this.fileName = fileName;
    }

    @Override
    public String getFilename() {
        return fileName;
    }
    @Override
    public long contentLength() {
        long estimate = length;
        return estimate == 0 ? 1 : estimate;
    }

    public void setLength(long length) {
        this.length = length;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值