天天看點

RestTemplate-檔案上傳下載下傳

目錄

一、概述

二、RestTemplate 配置

三、檔案上傳

四、檔案下載下傳

如果發現本文有錯誤的地方,請大家毫不吝啬,多多指教,歡迎大家評論,謝謝!

一、概述

在我們實際開發項目中,有需求通過HttpCliect調用另外一個服務去上傳,此時我們可以 RestTemplate 上傳和下載下傳來實作功能,是一個不錯的選擇。

二、RestTemplate 配置

/**
 * RestTemplate配置
 * 這是一種JavaConfig的容器配置,用于spring容器的bean收集與注冊,并通過參數傳遞的方式實作依賴注入。
 * "@Configuration"注解标注的配置類,都是spring容器配置類,springboot通過"@EnableAutoConfiguration"
 * 注解将所有标注了"@Configuration"注解的配置類,"一股腦兒"全部注入spring容器中。
 * 
 * @author Zou.LiPing
 *
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(@Qualifier("simpleClientHttpRequestFactory") ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        // 擷取資料逾時時間 毫秒
        factory.setReadTimeout(5000);
        return factory;
    }

}
           

三、檔案上傳

調用者

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("file")
public class FileController {

   private final RestTemplate restTemplate;


   /**
    *  restTemplate 上傳檔案
    *  通路位址: http://127.0.0.1:8110/file/uploadTest
    * @date: 2021/5/27 21:30
    * @return: java.lang.String
    */
   @GetMapping("uploadTest")
   public String uploadTest() {

      final String url = "http://127.0.0.1:8088/oss/file/uploadFile";
      MultiValueMap<String, Object> bodyParams = new LinkedMultiValueMap<>();
//      String filePath = "D:\\file\\video\\圖檔1\\1.jpg";
      String filePath = "D:\\file\\oss\\001.jpg";
      // 封裝請求參數
      FileSystemResource resource = new FileSystemResource(new File(filePath));
      bodyParams.add("file", resource);
      bodyParams.add("personId","p0001");
      bodyParams.add("reportNo","b0001");
      bodyParams.add("category",0);
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.MULTIPART_FORM_DATA);
      // heade 請求參數
      headers.add("Authorization", UUID.randomUUID().toString());
      HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyParams, headers);
      return  restTemplate.postForObject(url, requestEntity, String.class);
   }
}
           

生産者

/**
     * 檔案上傳
     */
    @PostMapping("/uploadFile")
    @ApiOperation(value = "檔案上傳")
    public String uploadFile(HttpServletRequest request,
                             @RequestParam("file") MultipartFile file,
                             @RequestParam("personId") String personId,
                             @RequestParam("reportNo") String reportNo,
                             @RequestParam("category") Integer category
                             ) {


        log.info("uploadFile.req personId={},reportNo={},category={}",personId,reportNo,category);
        log.info("token====>{}",request.getHeader("Authorization"));
        String url = fileService.uploadFile(FILE_HOST, file);
        return url;
    }
           

測試

 http://127.0.0.1:8110/file/uploadTest

RestTemplate-檔案上傳下載下傳

 生産者控制輸出

請求産生日志列印

: uploadFile.req personId=p0001,reportNo=b0001,category=0
: token====>109ac9c2-1448-41bb-9f6f-c99254bf7a1c
           

四、檔案下載下傳

調用者

/**
     * 檔案下載下傳
     * @param response
     * @date: 2021/5/31 10:40
     */
    @GetMapping("downloadTest")
    public void downloadTest(HttpServletResponse response) {

        String fileName = "edcb724a202d4497984cc48a240408d3.txt";
        String url = "http://127.0.0.1:8088/oss/file/downloadFile?fileName="+fileName;
        ResponseEntity<byte[]> rsp = restTemplate.getForEntity(url,byte[].class);
        BufferedInputStream bis = null;
        if (Objects.nonNull(rsp)) {
            byte[] body = rsp.getBody();
            if (Objects.nonNull(body)) {
                try {
                    log.info("檔案大小==>:{}", body.length);
                    String filename = fileName;
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
                    InputStream is = new ByteArrayInputStream(body);
                    bis = new BufferedInputStream(is);
                    OutputStream os = response.getOutputStream();
                    byte[] buffer = new byte[2048];
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
           

生産者

@Override
    public ResponseEntity<byte[]> downloadObject(String fileName) {

        fileName = "test/edcb724a202d4497984cc48a240408d3.txt";
        OSSObject ossObject = ossTemplate.getObject(fileName);
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        BufferedInputStream bis;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[10240];
        try {
            bis = new BufferedInputStream(ossObject.getObjectContent());
            while (true) {
                int len = bis.read(buf);
                if (len < 0) {
                    break;
                }
                bos.write(buf, 0, len);
            }
            //将輸出流轉為位元組數組,通過ResponseEntity<byte[]>傳回
            byte[] b = bos.toByteArray();
            log.info("接收到的檔案大小為:" + b.length);
            HttpStatus status = HttpStatus.OK;
            String imageName = "0001.txt";
            headers.setContentType(MediaType.ALL.APPLICATION_OCTET_STREAM);
            headers.add("Content-Disposition", "attachment;filename=" + imageName);
            entity = new ResponseEntity<>(b, headers, status);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return entity;
    }
           

測試

127.0.0.1:8110/upload/downloadTest

RestTemplate-檔案上傳下載下傳