Springboot文件下载代码

来源:互联网 发布:怎么提升淘宝买家等级 编辑:程序博客网 时间:2024/05/20 00:52

该案例简单实用,分享给大家:

直接上代码

@RequestMapping("/excel")public ResponseEntity<InputStreamResource> downFile(Long id) throws IOException{System.out.println("开始下载文件了");String filepath = "F:/aa.xlsx";FileSystemResource file = new FileSystemResource(filepath);HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.add("Cache-Control", "no-cache,no-store,must-revalidate");httpHeaders.add("Content-Disposition", String.format("attachment;filename=\"%s\"", file.getFilename()));httpHeaders.add("Pragma", "no-cache");httpHeaders.add("Expires", "0");return ResponseEntity.ok().headers(httpHeaders).contentLength(file.contentLength()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new InputStreamResource(file.getInputStream()));}@SuppressWarnings("resource")@RequestMapping("/image")public void getDownload(Long id,HttpServletRequest request,HttpServletResponse response){System.out.println("开始下载图片了");String fullPath = "F:/aa.jpg";File downloadFile = new File(fullPath);ServletContext context = request.getServletContext();//获取MIMI类型String mimeType = context.getMimeType(fullPath);if(mimeType == null){//设置二进制类型如果该文件的MIME类型没获取到mimeType = "application/octet-stream";System.out.println("context getMimeType is null");}System.out.println("MIME Type: "+mimeType);response.setContentType(mimeType);response.setContentLength((int) downloadFile.length());//设置响应头String headerKey = "Content-Disposition";String headerValue = String.format("attachment;filename=\"%s\"", downloadFile.getName());response.setHeader(headerKey, headerValue);//复制流,完成复制try {FileInputStream myStream = new FileInputStream(downloadFile);IOUtils.copy(myStream, response.getOutputStream());response.flushBuffer();} catch (Exception e) {System.out.println("复制图片报异常了");e.printStackTrace();}}


0 0