欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

文件下载

程序员文章站 2022-07-08 17:57:29
前端代码一个a标签,href就是要访问的controller的路径,以下是文件下载Java代码,chrome要选高级,然后配置,不然每次都保存默认位置,不会弹出另存框 //文件下载 @RequestMapping(value = "/downFile",method = RequestMethod.GET) public void downloadImage(String fileName,HttpServletRequest request, HttpServletRespons...

前端代码一个a标签,href就是要访问的controller的路径,以下是文件下载Java代码,chrome要选高级,然后配置,不然每次都保存默认位置,不会弹出另存框
文件下载

    //文件下载
    @RequestMapping(value = "/downFile",method = RequestMethod.GET)
    public void downloadImage(String fileName,HttpServletRequest request, HttpServletResponse response) {
        //处理一下文件名,不然中文乱码
        fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
        //文件路径
        String fileUrl = "C:\\test\\123.txt";
        if (fileUrl != null) {
            File file = new File(fileUrl);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

本文地址:https://blog.csdn.net/a3562323/article/details/109276929