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

  • 相关阅读:
    合并报表优化记录
    如何在后台代码中执行原生sql?
    eclipse从数据库逆向生成Hibernate实体类
    用Eclipse进行远程Debug代码
    hibernate自动生成数据库表
    hibernate自动生成数据库表
    php通过UNIX源码编译安装
    php设置方法
    php其他配制选项
    终于做出了目录认证!
  • 原文地址:https://www.cnblogs.com/lh-V/p/3682628.html
Copyright © 2011-2022 走看看