• 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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    下载

    下载只需要注意返回值为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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

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

  • 相关阅读:
    MQ消息队列(二)——RabbitMQ进阶,保证消息的可靠性
    【快速上手系列】用于登录的验证码制作(ValidateCode)和Javaweb自带的老式验证码快速上手
    好看又炫酷的网页特效例子收集
    CentOS上安装JDK的详细教程
    每日五问(java)
    强化学习案例复现(2)--- MountainCar基于DQN
    apollo中配置map,list
    javascript深浅拷贝
    超市商品管理系统 毕业设计 JAVA+Vue+SpringBoot+MySQL
    拿下!这些证书可以帮你职场晋升!(PMP/CSPM/NPDP)
  • 原文地址:https://blog.csdn.net/backbug/article/details/133107494