java下载文件工具类

java下载文件工具类

package com.cms.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.http.HttpServletResponse;

/**
 * 下载工具类
 * @author abc
 *
 */
public class DownloadUtils {
     
    /**
     * 根据网络url下载文件
     * @throws MalformedURLException 
     */
    public static void DownloadByUrl(String urlPath,HttpServletResponse response) throws Exception{        
         URL url = new URL(urlPath);
         //文件后缀名
         String str = url.getFile().substring( url.getFile().lastIndexOf(".")+1);
         //文件名
         String filename = url.getFile().substring(url.getFile().lastIndexOf("/")+1,url.getFile().lastIndexOf("."));
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();      
        int code = conn.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }
        InputStream fis = new BufferedInputStream(conn.getInputStream());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        // 以流的形式下载文件。
       int count = 0; 
        byte[] buffer = new byte[1024*8];  
        int read=0;
        //如果没有数据了会返回-1;如果还有会返回数据的长度
        while ((read = fis.read(buffer))!=-1) {
            count+=read;
            //读取多少输出多少
            toClient.write(buffer,0,read);
          }    
        toClient.flush();
        toClient.close();
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" +filename+"."+str);
        response.addHeader("Content-Length", "" +count);   
        response.setContentType("application/octet-stream");       
      
        
    }
    
    
}

猜你喜欢

转载自www.cnblogs.com/qq376324789/p/10862997.html