zoukankan      html  css  js  c++  java
  • Java 实现下载

    效果就是点击就可以下载到本机。

    • 前台代码示例
    • 后台代码示例

    前台代码示例

    <a target='_self' href='../downTask/downloadFileToLocal?fileName=59.csv' >

    后台代码示例

    @RequestMapping(value = "/downloadFileToLocal", method = RequestMethod.GET)
        public void downloadFileToLocal(String fileName,HttpServletRequest request,  HttpServletResponse response) throws IOException {
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("multipart/form-data");
                    response.setHeader("Content-Disposition", "attachment;fileName="
                            + fileName);
                    OutputStream os = response.getOutputStream();
                    try {
                        String path = Helper.getAppPath();
                        log.debug("========="+path);
                        InputStream inputStream = new FileInputStream(new File(path
                                + File.separator + fileName));
                        byte[] b = new byte[2048];
                        int length;
                        while ((length = inputStream.read(b)) > 0) {
                            os.write(b, 0, length);
                        }
                        inputStream.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally{
                         os.close();
                    }
            }

    注:我这个框架是用的SpringMVC,自行修改吧。

    Code is read far more than it's written
  • 相关阅读:
    Tomcat December 31,2019
    XML
    Java
    mysql8.0.16安装(补) September 24,2019
    乱码中的编码和解码
    idea优化
    新版web.xml
    重定向和请求转发
    web下载文件设置的头信息
    响应状态码
  • 原文地址:https://www.cnblogs.com/ChickenTang/p/5655399.html
Copyright © 2011-2022 走看看