JAVA浏览器下载resource目录下的TXT文件

版权声明:本文为HCG原创文章,未经博主允许不得转载。请联系[email protected] https://blog.csdn.net/qq_39455116/article/details/82378946

JS代码

   /**下载导入模板*/
    $("#downloadTemplate").click(function(){
        window.location.href="/td/datacube/dmpTagsUpload/downloadTemplate";
    })

后台代码

  //获取resource目录的相对路径
        String path = request.getSession().getServletContext().getRealPath("/");
        if (!path.endsWith(File.separator)) {
            path = path + File.separator;
        }
        //获取模板txt文件在resource目录下的相对路径
        String relativeFilePath = File.separator+"resource"+File.separator+"template"+
                        File.separator+"dmpTagsUpload"+File.separator;
        String fileName ="种子模板.txt";
        File file=new File(path+File.separator+relativeFilePath+fileName);//old

        try {

            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path+relativeFilePath+File.separator+fileName));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            //设置文件名
            response.addHeader("Content-Disposition",
                    " attachment;filename=" + new String(filename.getBytes(),"iso-8859-1"));
//            response.addHeader("Content-Disposition", "attachment;filename=" +filename);
//            System.out.println("文件名1"+new String(filename.getBytes()));
            //设置文件打下
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }














猜你喜欢

转载自blog.csdn.net/qq_39455116/article/details/82378946