Download file using Java IO stream

   @RequestMapping(value = "download")
    public String download(HttpServletResponse response, Model model) { 
        
        //Find the directory where the file is located by the file name
        String URL = "D:/one/two.txt";
        //Get to download The file
        File file = new File(URL);
        
        //if the file does not exist

        if(!file.exists()){

            //If the file does not exist, process it

           int i=1/0;//The system will report an error, the divisor cannot be 0.

           // return "modules/cms/front/themes/"+site.getTheme()+"/frontError";
        }
        
        InputStream inputStream = null;  
        OutputStream outputStream = null;  
      //create buffer
        byte[] b= new byte[1024 ];  
        int len ​​= 0;  
        try {  
             //Read the file to be downloaded and save it to the file
             inputStream inputStream = new FileInputStream(file);  
             outputStream = response.getOutputStream();  
             response.setContentType("application/force-download" );  
             String filename = file.getName();  
             //Set the response header to control the browser to download the file
             response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));  
             response.setContentLength( (int) file.length( ) );  
             //The loop will input The content in the stream is read into the buffer      
             while((len = inputStream.read(b)) != -1){
                 //Output the content of the buffer to the browser to realize the file download
                  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;

    }


Just add the access address to the link.

   

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325906534&siteId=291194637