web开发中文件下载

 

1,

<a href="后台文件的url路径">下载</a>

单击下载链接,浏览器就会弹出文件下载提示。如果浏览器认为自己可以打开,也许会直接打开

2,

访问后台action或controller或servlet,

获取response.getOutputStream();

获取到后台文件的输入流

输出到输出流(response会带OutputStream到客户端浏览器,浏览器会自动获取)

 

代码:

@RequestMapping("/FileManager_download.jspx")
	public void fileDownload(HttpServletRequest request,
			HttpServletResponse response, String fileName, String fileUrl)
			throws Exception {
		String filename  = new String(fileName.getBytes("ISO-8859-1"),"utf-8");//浏览器传递数据时久不用编码啦
		System.out.println(filename);
		String downloadFileDir = request.getSession().getServletContext()
				.getRealPath("downLoadFile");
		String srcFileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1,
				fileUrl.length());
		File file = new File(downloadFileDir, srcFileName);
		InputStream inputStream = null;
		OutputStream outputStream = null;
		byte[] b = new byte[1024];
		int len = 0;
		if (file.exists()) {
			inputStream = new FileInputStream(file);
			outputStream = response.getOutputStream();
			response.setContentType("application/force-download");
			response.addHeader("Content-Disposition", "attachment; filename="
					+new String(filename.getBytes("UTF-8"),"ISO-8859-1"));//为什么ISO-8859-1到前台不会出现乱码呢???
			response.setContentLength((int) file.length());
			while ((len = inputStream.read(b)) != -1) {
				outputStream.write(b, 0, len);
			}
		}
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e) {
			}
		}
		if (outputStream != null) {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

  

 http://blog.csdn.net/tianping168/article/details/2698221

posted on 2014-04-23 12:26  V-LH 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lh-V/p/3682628.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值