檔案下載下傳
在使用Spring的檔案下載下傳和上傳功能時,可以直接向前端傳回ResponseEntity<byte[]>類型的資料。功能代碼如下:
public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, String url, String fileName)
throws Exception {
InputStream in = new FileInputStream(new File(url));
byte[] body = new byte[in.available()];
in.read(body);
fileName = new String(fileName.getBytes("gbk"), "iso8859-1") + ".exe"; //設定檔案名
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=" + fileName);
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body, headers, status);
return responseEntity;
}
以上代碼根據使用中的不同需要對應替換。但是,在調用結束後浏覽器确實下載下傳了檔案,但是打開發現出現亂碼的情況,并且檔案會比真實檔案稍大一些。
解決亂碼
在使用SpringMVC時,我們注意到出現這種問題的原因是JSON資料在比特流傳遞的時候的編碼解碼問題導緻了亂碼的出現。我們隻需要配置ByteArrayHttpMessageConverter便可以解決。但是SpringBoot沒有xml配置檔案,我們應該如何操作呢?
- 在SpringBoot的配置檔案中添加ByteArrayHttpMessageConverte的Bean。
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
return new ByteArrayHttpMessageConverter();
}
- 在注冊轉換器configureMessageConverters方法中添加該Bean。
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(byteArrayHttpMessageConverter());
converters.add(...); //其他的轉換器
}
前端測試
在Controller中做好RequestMapping的方法之後,将比特流傳回給前端,前端直接打開新的網頁開始下載下傳。