Springboot文件下载代码

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

直接上代码

@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();
		}
		
	}


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值