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}×tamp={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等工具类,进行其他处理。

你可能感兴趣的:(文件上传与下载,开发语言,java)