【文件下载】java使用浏览器从后台服务器下载文件

需求分析说明

前一段时间项目中有一个需求:前端页面下载一个合同文本是直接拿着文件地址去服务器上进行下载,这种直接把文件服务器暴露给用户下载的方式是不安全的;于是需要进行改造,前端页面访问后台方法,后台查询出文件地址然后进行下载,将输出流返给前端。

代码说明

首先你要知道你自己下载文件的路径,这个自己可以根据项目需求另写方法查询出来地址,然后当参数传递过来。

public void downloadFile(String fileUrl) throws Exception{
	BufferedInputStream bis = null;
	BufferedOutputStream bos = null;
	ServletOutputStream bos = null;
	try{
		URL url = new URL(fileUrl);
		HttpURLConnection connection = (HttpURLConnection)url.openConnection;
		// 设置请求方式
		connection.setRequestMethod("GET");
		// 获取连接
		connection.connect();
		// 获取输入流
		InputStream is = connection.getInputStream();
		bis = new BufferedInputStream (is);
		// 获取返给前端的response并设置参数
		this.getServletResponse().reset();
		this.getServletResponse().setContentType("text/plain");
		// fileName 前台浏览器上面会显示下载的文件名
		this.getServletResponse().addHeader("Content-Disposition","attachment;filename\""+fileName);
		sos = this.getServletResponse().getOutputStream();
		bos = new BufferedOutputStream(sos);
		int bytes;
		byte[] byteArr = new byte[1024];
		while((bytes = bis.read(byteArr)) != -1){
			bos.write(byteArr,0,bytes);
		}
		// 将输出流bos返回给前端
		return ;
	} catch(Exception e){
		log.error("文件下载失败",e);
	} finally {
		try{
			if(bis != null){
				bis.close();
			}
			if(bos != null){
				bos.close();
			}
			if(sos != null){
				sos.close();
			}
		} catch(IOException e) {
			e.printStackTrace()
		}
	}
}

版权声明:本文为LazyCancerPatiens原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。