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

原文地址:https://www.cnblogs.com/lh-V/p/3682628.html