vue下载文件并重命名

时间:2025-04-05 12:57:11
/** * 下载附件 * @param response * @param fileName */ @GetMapping(value = "/downloadAttachment") public ResponseEntity<?> downloadAttachment(final HttpServletResponse response, @RequestParam("fileName") String fileName) { InputStream inputStream = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { // 获取文件信息 ObjectStat objectStat = template.getObjectInfo(bucketName, fileName); // 设置响应头 response.setHeader("content-type", objectStat.contentType()); response.setContentType(objectStat.contentType()); // 获取文件输入流 inputStream = template.getObject(bucketName, fileName); outputStream = this.readInpurStream(inputStream); ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray()); return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .header(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s", URLEncoder.encode(fileName+".pdf", "UTF-8"))) .body(resource); } catch (Exception e) { log.error("导出附件失败:",e); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("下载文件出现异常"); } } /** * 将input流转化为ByteArrayOutputStream * @param input * @return * @throws Exception */ public ByteArrayOutputStream readInpurStream(InputStream input) throws Exception{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; try { while ((len = input.read(buffer)) > -1) { baos.write(buffer, 0, len); } baos.flush(); } catch (IOException e) { throw new Exception("Illegal flow."); } finally { try { input.close(); } catch (IOException e) { log.error("file stream shutdown failed."); } } return baos; }