• 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等工具类,进行其他处理。

  • 相关阅读:
    SpringBoot进阶学习(三)---测试
    VUE系列 --- 网络模块axios(二 )
    伯俊ERP和金蝶云星空接口打通对接实战
    Mybatis、hibernate常用sql
    VS采用nuget配置OpenGL
    读了很多书,学了很多语言,专业知识远超普通大众,程序员1024依然要送外卖
    【C++】动态内存管理 ③ ( C++ 对象的动态创建和释放 | new 运算符 为类对象 分配内存 | delete 运算符 释放对象内存 )
    mybatis 生成器,是否功能实现,需写测试类
    使用DevEco Studio开发一个hallo world并安装到你的遥遥领先里面
    RabbitMQ笔记(交换机,发布确认,延时队列,死信队列,整合SpringBoot)
  • 原文地址:https://blog.csdn.net/backbug/article/details/133107494