RestTemplate上传、下载文件

上传

上传文件分两种:
①要处理的文件本身存在当前文件系统下
②要处理的文件只是个临时文件,或者说是文件流的形式存在

在以下代码中会分别标注:

private static void upAttach() {
    String uploadUrl = "http://192.168.1.10/upload";
    String appId = "";
    String accessKey = "";
    String filePath = "";
    String originalFilename = "test.xlsx";
    
    long currentTimeMillis = System.currentTimeMillis();
    String timeMillis = String.valueOf(currentTimeMillis);
    // 文件路径
    String base64key = Base64.encodeBase64String(filePath.getBytes());
    String sign = getSign(appId, base64key, timeMillis, accessKey);

    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>(3);
    
    // @Deprecated 
    // Write to temporary file and then process, need to be deleted and tends to generate too much garbage
    // Path tempFile = Files.createTempFile("upload-file", ".txt");
    // Files.write(tempFile, file.getBytes());
    // params.add("file", new FileSystemResource(tempFile.toFile()));

	// ============================== 这里是重点 ==============================
    // ① 文件存在,直接获取文件输入流即可
	File file = new File("c:\\test.xlsx");
    params.add("file", new InputStreamResource(file.getInputStream(), originalFilename));

	// ② 临时文件,如MultipartFile,获取其字节流来处理
	MultipartFile multipartFile = null;
	byte[] byteArray = multipartFile.getBytes();
    ByteArrayResource byteArrayResource = new ByteArrayResource(byteArray) {
        @Override
        public String getFilename() {
        	// 这里不指定文件名的话,上传过去的文件名会乱码
            return originalFilename;
        }
    };
    params.add("file", byteArrayResource);
	// ========================================================================

	// 其他参数按需采用	
    // key为文件路径
    params.add("key", filePath);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    headers.add("x-fs-timestamp", timeMillis);
    headers.add("x-fs-appid", appId);
    headers.add("x-fs-sign", sign);
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);

    RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);
    restTemplate.postForObject(uploadUrl, requestEntity, JSONObject.class);
}


/** 加密 **/
private static String getSign(String appId, String base64key, String timestamp, String accessKey) {
    String sign = appId + "|" + base64key + "|" + timestamp;
    return new HmacUtils(HmacAlgorithms.HMAC_SHA_256, accessKey).hmacHex(sign);
}

下载

下载只需要注意返回值为byte[]即可:

// resource为文件唯一标识,按需采用
public static final byte[] dwAttach(String resource) {
    String appId = "";
    String accessKey = "";

    long currentTimeMillis = System.currentTimeMillis();
    String timeMillis = String.valueOf(currentTimeMillis);
    String base64key = Base64.encodeBase64String(resource.getBytes());
    String sign = getSign(appId, base64key, timeMillis, accessKey);

    String downloadUrl = "http://192.168.1.10?appid={appId}&timestamp={timestamp}&sign={sign}";
    HashMap<String, Object> uriVariables = new HashMap<>(5);
    uriVariables.put("appId", appId);
    uriVariables.put("timestamp", timeMillis);
    uriVariables.put("sign", sign);
    RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);

    return restTemplate.getForObject(downloadUrl, byte[].class, uriVariables);
}

后续可通过new ByteArrayInputStream(byte[])转换成流,或者org.springframework.util.FileCopyUtils, org.apache.commons.io.FileUtils等工具类,进行其他处理。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值