用Java IO流实现下载文件

用Java IO流实现下载文件  @RequestMapping(value="download")   publicStringdownload(HttpServletResponseresponse,Modelmodel){             //通过文件名找出文件的所在目录      StringURL="D:/one/two.txt";      //得到要下载的文件…

大家好,又见面了,我是你们的朋友全栈君。   @RequestMapping(value = “download”)

    public String download(HttpServletResponse response, Model model) { 

        

        //通过文件名找出文件的所在目录

        String URL = “D:/one/two.txt”;

        //得到要下载的文件

        File file = new File(URL);

        

        //如果文件不存在

        if(!file.exists()){

            //如果文件不存在,进行处理

           int  i=1/0;//系统会报错,除数不能为0.

           // return “modules/cms/front/themes/”+site.getTheme()+”/frontError”;

        }

        

        InputStream inputStream = null;  

        OutputStream outputStream = null;  

      //创建缓冲区

        byte[] b= new byte[1024];  

        int len = 0;  

        try {  

             //读取要下载的文件,保存到文件输入流

             inputStream = new FileInputStream(file);  

             outputStream = response.getOutputStream();  

             response.setContentType(“application/force-download”);  

             String filename = file.getName();  

             //设置响应头,控制浏览器下载该文件

             response.addHeader(“Content-Disposition”,”attachment; filename=” + URLEncoder.encode(filename, “UTF-8”));  

             response.setContentLength( (int) file.length( ) );  

             //循环将输入流中的内容读取到缓冲区当中      

             while((len = inputStream.read(b)) != -1){

                 //输出缓冲区的内容到浏览器,实现文件下载

                  outputStream.write(b, 0, len);  

             }

                

         } catch (Exception e) {  

                e.printStackTrace();  

         }finally{  

                if(inputStream != null){  

                    try {  

                        inputStream.close();  

                        inputStream = null;  

                    } catch (IOException e) {  

                        e.printStackTrace();  

                    }  

                }  

                if(outputStream != null){  

                    try {  

                        outputStream.close();  

                        outputStream = null;  

                    } catch (IOException e) {  

                        e.printStackTrace();  

                    }  

                }  

            }

           

        return null;

    }

在链接中加入该访问地址即可。

   

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/138720.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号