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(); 
        }
  • 相关阅读:
    关于json字符串与实体之间的严格验证
    SQL Pretty Printer 一款值得你拥有的MSSQL格式化插件
    ABP增加记录EFCore 生成数据库脚本日志到新的txt文件
    Multiple types were found that match the controller named 'Auth'.
    sqlserver 交叉去重
    sqlserver分组排序取前三条数据
    C# 读取.resx资源文件写入到json文件中
    SqlServer根据经纬度排序
    .net core 简单定时程序
    使用游标,查询一张的数据往另外三张表里面添加数据
  • 原文地址:https://www.cnblogs.com/xiufengd/p/9516274.html
Copyright © 2011-2022 走看看