zoukankan      html  css  js  c++  java
  • java 文件下载

    文件下载的主要思路是前台触发form的post请求,后台将文件获取后写入输出流中。

    1、前台定义form表单

    <form id="downForm" method="post">
        <input type="hidden" id="filepath" name="filepath" value="">
        <input type="hidden" id="filename" name="filename" value="">
    </form>

    2、后台定义相关触发方法

    function downForm(fileName,filePath){
        $("#downForm").attr("action","/demand/down");
        $("#filepath").val(filePath);
        $("#filename").val(fileName);
        $("#downForm").submit();
    }

    3、后台接收参数

    public void down(HttpServletRequest request,HttpServletResponse response){
            request.setAttribute("filePath", request.getParameter("filepath"));
            request.setAttribute("fileName", request.getParameter("filename"));
            try {
                fileService.fileDownlaod(request,response, true);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

    4、实现写入操作

      

        public void fileDownlaod(HttpServletRequest request,HttpServletResponse response, boolean isOnLine) throws Exception{
            String filepath = (String) request.getAttribute("filePath");
            String filename = (String) request.getAttribute("fileName");
            File f = new File(filepath);
            if (!f.exists()) {
                throw new GlobalException("文件不存在");
            }
            response.reset(); // 非常重要
            if (isOnLine) { // 在线打开方式
                URL u = new URL("file:///" + filepath);
                response.setContentType(u.openConnection().getContentType());
                response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            } else { // 纯下载方式
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("gb2312"), "iso-8859-1"));
            }
            OutputStream out = response.getOutputStream();
            BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = br.read(buf)) > 0){
                out.write(buf, 0, len);
            }
            br.close();
            out.close(); 
        }
  • 相关阅读:
    【转】C#中的虚方法
    【转】ASP.NET 2.0中Page事件的执行顺序
    OWC ChartSpace控件的使用
    Ext对基本类型的扩展
    OWC PivotTable的使用方法
    .net中线程同步的典型场景和问题(1)
    python中使用汉字
    如何取消后台线程的执行
    yaffs2根文件系统的构建过程
    Fuck self.delegate = self
  • 原文地址:https://www.cnblogs.com/xiufengd/p/9516274.html
Copyright © 2011-2022 走看看