java 远程下载服务器的文件

废话不多说,直接上代码:

public void downloadChineseFileByOutputStream(HttpServletRequest req,

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

            throws FileNotFoundException, IOException {  

        String realPath = path;//req.getSession().getServletContext().getRealPath(path);//获取要下载的文件的绝对路径  

        String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);//获取要下载的文件名  

        

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

      //根据浏览器类型处理文件名称    处理火狐浏览器下载文件名乱码

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

        {

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

        }

        else//其他浏览的中文名称编码

        {

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

        }

        

        //设置content-disposition响应头控制浏览器以下载的形式打开文件,中文文件名要使用URLEncoder.encode方法进行编码,否则会出现文件名乱码  

        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);//设置是否要从 URL 连接读取数据,默认为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);//将缓冲区的数据输出到客户端浏览器  

            out.flush();

        } 

        out.close();

        in.close();

    } 

猜你喜欢

转载自luckylearn.iteye.com/blog/2393594