• 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

  • 相关阅读:
    swift2.0学习之拓展
    CSDN处理问题神速,顶你,为你点32个赞!
    quick-cocos2d-x教程7:程序框架内framework文件夹分析
    Android自己定义Toast
    leetcode: Add Digits
    Effective Java:对于全部对象都通用的方法
    动态规划法-01背包问题
    loosejar原理简要分析
    eclipse中Client/Server程序生成exe
    Spring 新手教程(三) 注入和自己主动装配
  • 原文地址:https://www.cnblogs.com/lh-V/p/3682628.html
Copyright © 2020-2023  润新知