SpringMVC使用ResponseEntity實現文件下載,及圖片base64的字節數組上傳於下載


本文主要通過ResponseEntity<byte[]>實現文件下
該類實現響應頭、文件數據(以字節存儲)、狀態封裝在一起交給瀏覽器處理以實現瀏覽器的文件下載。
ResponseEntity參數解釋:ResponseEntity(T body, MultiValueMap<String, String> headers, HttpStatus statusCode)
其中ResponseEntity<T> extends HttpEntity<T>,很明顯的繼承關系,HttpEntity是一個實體類,在new ResponseEntity<byte[]>(b, headers, statusCode);這句初始化的時候,會將T body, MultiValueMap<String, String> headers兩個參數傳給父類,本類中存放狀態碼,在HttpEntity類的源碼中可以看到:

public HttpEntity(T body, MultiValueMap<String, String> headers) {
this.body = body;
HttpHeaders tempHeaders = new HttpHeaders();
if (headers != null) {
tempHeaders.putAll(headers);
}
//將header頭轉變成只能讀取的對象,而不是寫入的對象。
this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders);
}

HttpHeaders類說明:表示HTTP請求和響應頭,將字符串頭名映射到字符串值的列表。
在這里為什么要用HttpHeaders類,是因為MultiValueMap接口的實現類是:HttpHeaders、LinkedMultiValueMap以及靜態類MultiValueMapAdapter
話不多說直接上代碼:

//下載練習

@GetMapping("/download")
public ResponseEntity<byte[]> download(@RequestParam(name = "id") Long id, HttpServletRequest request) {
TemplateDto byId = getBaseService().findById(id);
HttpHeaders headers = new HttpHeaders();
String fileName = null;
try {
fileName = FileExtraUtils.handleFileName(request, "download.pdf");
} catch (UnsupportedEncodingException e) {
//ignore
log.warn("文件名處理出錯", e);
}
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //二進制流(或者字節數組)的形式返回

return new ResponseEntity<>(byId.getTemplaeContent(), headers, HttpStatus.OK);
}

或者根據臨時文件保存的路徑獲取輸入流,然后copy給輸出流進行下載
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(filePath);
outputStream = response.getOutputStream();
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename=" + info.getFileName());
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}



//上傳文件並保存
@PostMapping("/upload")
public void upload(@Param("file") MultipartFile file, HttpServletResponse response) throws IOException {
File tempFile;
try {
tempFile = File.createTempFile(file.getOriginalFilename(), ".pdf");
file.transferTo(tempFile);
HashMap data = new HashMap();
data.put("fileName", tempFile.getCanonicalPath());
data.put("displayName", file.getOriginalFilename());
ResultDto dto = ResultDtoFactory.toAckData(data);
response.setContentType("text/html; charset=utf-8");
response.getWriter().write(JSON.toJSONString(dto));
} catch (IOException e) {
log.error("保存文件失敗", e);
ResultDto dto = ResultDtoFactory.toNack("文件上傳失敗");
response.setContentType("text/html; charset=utf-8");
response.getWriter().write(JSON.toJSONString(dto));
}
}

@Override
public ResultDto create(TemplateDto templateDto) {
String fileName = templateDto.getFileName();
try (FileInputStream fis = new FileInputStream(new File(fileName))) {
templateDto.setTemplaeContent(IOUtils.toByteArray(fis));
} catch (IOException e) {
log.error("讀取模版內容出錯", e);
return ResultDtoFactory.toNack("讀取模板內容出錯,請重新上傳");
}
getBaseService().save(templateDto);
return ResultDtoFactory.toAck();
}

//另外圖片的上傳於下載
@PostMapping("/upload")
public void upload(@RequestParam String configKey, MultipartFile file, HttpServletResponse response) throws IOException {
ConfigDto configDto = new ConfigDto();
configDto.setConfigKey(configKey);
String base64Content = Base64Utils.encodeToString(IOUtils.toByteArray(file.getInputStream()));
configDto.setConfigValue(base64Content);
configService.save(configDto);
ResultDto resultDto = ResultDtoFactory.toAck();
response.setContentType("text/html; charset=utf-8");
response.getWriter().write(JSON.toJSONString(resultDto));
}

@GetMapping("/download")
public void download(@RequestParam(required = true) String configKey, HttpServletResponse response) throws IOException {
List<ConfigDto> byKey = configService.findByKey(configKey);
if (CollectionUtils.isNotEmpty(byKey)) {
ConfigDto configDto = byKey.get(0);
if(configDto!=null){
String base64Content = configDto.getConfigValue();
byte[] bytes = Base64Utils.decodeFromString(base64Content);
IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
response.getOutputStream().flush();
}
}
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM