springMVC实现文件下载

springMVC实现文件下载

一、文件下载原理
1、设置 response 响应头
2、读取文件 -- InputStream
3、写出文件 -- OutputStream
4、执行操作
5、关闭流 (先开后关)

二、实现代码

@RequestMapping(value="/downloadFile")
	public String downloads(HttpServletResponse response) throws Exception{
		String	path = "C:/";
		String  fileName = "default.png";
		//1、设置response 响应头
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", 
				"attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
		
  File file = new File(path,fileName);
		//2、 读取文件--输入流
		InputStream input=new FileInputStream(file);
		//3、 写出文件--输出流
		OutputStream out = response.getOutputStream();
		byte[] buff =new byte[1024];
		int index=0;
		//4、执行 写出操作
		while((index= input.read(buff))!= -1){
			out.write(buff, 0, index);
			out.flush();
		}
		out.close();
		input.close();
		return null;
	}	
注: 直接请求url: "/downloadFile",即可实现文件下载。 (需:C盘有一个 default.png 的文件)



三、使用spirng 自带的 ResponseEntity 实现
@RequestMapping(value="/downloadEntity")
	public ResponseEntity<byte[]> downloadsEntity(HttpServletRequest request) throws Exception{
		String	path = "C:/";
		String  fileName = "default.png";
		File file=new File(path,fileName);
		if(!file.isFile()){
			return null;
		}
		@SuppressWarnings("resource")
		InputStream input=new FileInputStream(file);
		byte[] buff=new byte[input.available()]; // 获取文件大小
		input.read(buff) ;
		HttpHeaders headers=new HttpHeaders();
		headers.add("Content-Disposition", "attachment;filename="+fileName);
		HttpStatus status=HttpStatus.OK;
		ResponseEntity<byte[]> entity=new ResponseEntity<byte[]>(buff,headers,status);
		return  entity;
	}


四、前端页面
1、html页面直接下载: <a href="/downloads/downloadFile">点击下载</a><br><br>

2、js 代码下载: 
a. html:<button id="btn_location">location下载</button><br><br>
b. js : 
  $("#btn_location").click(function(){
			window.location.href="/downloads/downloadFile";
		});



  • 8
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值