zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    A1061 Dating [字符串比较]
    A1058 A+B in Hogwarts [进制转换]
    A1027 Colors in Mars[简单模拟--进制转换]
    A1031 Hello World for U[图形输出]
    刷PAT的一些思考—Day 1
    A1009 Product of Polynomials[简单模拟--多项式相乘]
    A1002 A+B for Polynomials[简单模拟--多项式相加]
    A1046 Shortest Distance [简单模拟--卡算法复杂度]
    1009 说反话
    usb之配置描述符
  • 原文地址:https://www.cnblogs.com/lh-V/p/3682628.html
Copyright © 2011-2022 走看看