java remote download server file

Without further ado, let’s go directly to the code:

public void downloadChineseFileByOutputStream(HttpServletRequest req,

    HttpServletResponse response,@RequestParam("path") String path)  

            throws FileNotFoundException, IOException {  

        String realPath = path;//req.getSession().getServletContext().getRealPath(path);//Get the absolute path of the file to download  

        String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);//Get the file name to download  

        

        String agent = req.getHeader("USER-AGENT").toLowerCase();

      //Process file name according to browser type

        if(agent != null && agent.toLowerCase().indexOf("firefox") > 0)

        {

        fileName =  new String(fileName.getBytes("UTF-8"),"ISO-8859-1");   

        }

        else//Other browsing Chinese name codes

        {

        fileName =  java.net.URLEncoder.encode(fileName, "UTF-8");

        }

        

        //Set the content-disposition response header to control the browser to open the file in the form of download. The Chinese file name should be encoded using the URLEncoder.encode method, otherwise the file name will be garbled  

        response.reset();

        response.setHeader("content-disposition", "attachment;filename="+fileName);  

        response.setContentType("application/octet-stream");  

      

        URL url = new URL(realPath);   

        HttpURLConnection uc = (HttpURLConnection) url.openConnection();  

        uc.setDoInput(true);//Set whether to read data from the URL connection, the default is true  

        uc.connect();  

        InputStream in = uc.getInputStream(); 

       /* File file = new File(realPath);

        InputStream in = new FileInputStream(file);*/

       

        int len ​​= 0;  

        byte[] buffer = new byte[1024];  

        OutputStream out = response.getOutputStream();  

        while ((len = in.read(buffer)) > 0) {  

            out.write(buffer,0,len);//Output the buffer data to the client browser  

            out.flush();

        } 

        out.close();

        in.close();

    } 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326802855&siteId=291194637