网络文件下载 下载文件-通过流 保存文件-网络文件
DownloadUtil.java
package zjweb.download.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.Serializable; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import zj.check.util.CheckUtil; import zj.io.util.FileUtil; import zjweb.download.pageModel.DownloadPage; import zjweb.download.pageModel.IDownload; import zjweb.util.WebUtil; import zjweb.util.WebUtil.Browser; /** * 文件下载类<br> * * @version 1.00 (2011.12.02) * @author SHNKCS 张军 {@link <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>} */ public class DownloadUtil implements Serializable { private static final long serialVersionUID = 1L; private transient static final Logger log = Logger.getLogger(DownloadUtil.class); /** * 下载文件-通过流 * * @param srcPath * 下载源文件 * @param newFileName * 重全名文件 * @return true:成功,false:失败 * @throws Exception */ public static void streamDownload(DownloadPage page, HttpServletResponse response) throws Exception { streamDownload(page, response, null); } /** * 下载文件-通过流 * * @param srcPath * @param newFileName * @return true:成功,false:失败 * @throws Exception */ public static void streamDownload(DownloadPage page, HttpServletResponse response, IDownload download) throws Exception { BufferedOutputStream bos = null; BufferedInputStream fis = null; try { // HttpServletResponse response = ServletActionContext.getResponse(); fis = new BufferedInputStream(new FileInputStream(page.getSrcPath())); if (CheckUtil.isNull(page.getNewFileName())) { // 取得文件名。 page.setNewFileName(FilenameUtils.getName(page.getSrcPath())); } if (page.isAutoAddExtension()) { page.setNewFileName(page.getNewFileName() + "." + FilenameUtils.getExtension(page.getSrcPath())); } boolean isFirefox = WebUtil.getBrowser(page.getUserAgent()).get(Browser.FIREFOX); if (isFirefox) { page.setNewFileName(new String(page.getNewFileName().getBytes("UTF-8"), "iso8859-1")); } else { page.setNewFileName(URLEncoder.encode(page.getNewFileName(), "UTF8")); } // byte[] buffer = new byte[fis.available()]; // fis.read(buffer); // 清空response 清空buffer,设置页面不缓存 response.reset(); // 设置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + page.getNewFileName()); response.addHeader("Content-Length", "" + fis.available()); bos = new BufferedOutputStream(response.getOutputStream()); int blen = 1024 * 5; byte[] b = new byte[blen]; int len = 0; while ((len = fis.read(b, 0, blen)) != -1) { bos.write(b, 0, len); } response.setContentType("application/octet-stream"); // toClient.write(buffer); bos.flush(); log.debug("成功:下载源文件地址:" + page.getSrcPath()); if (download != null) { download.after(page); } } finally { if (bos != null) { try { bos.close(); } catch (Exception e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (Exception e) { e.printStackTrace(); } } } } /** * 保存文件 * * @param srcPath * @param descPath * @param true:成功,false:失败 * @throws Exception */ public static void saveFromURL(DownloadPage page) throws Exception { BufferedOutputStream bos = null; BufferedInputStream fis = null; InputStream is = null; try { // 以流的形式下载文件。 URL url = new URL(page.getSrcPath()); URLConnection urlConnection = url.openConnection(); // 下面解决Server returned HTTP response code: 403 for URL urlConnection.setRequestProperty("Accept-Charset", "utf-8"); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); urlConnection.connect(); is = urlConnection.getInputStream(); fis = new BufferedInputStream(is); // 取得目标文件路径 if (page.getDescPath() == null || page.getDescPath().equals("")) { String[] paths = FileUtil.getFileNameExtension(page.getSrcPath()); if (paths.length > 2) { page.setDescPath(paths[1] + paths[2]); } else { File file = new File(page.getSrcPath()); page.setDescPath(file.getName()); } } // byte[] buffer = new byte[fis.available()]; // fis.read(buffer); File fileDesc = new File(page.getDescPath()); String[] extension = FileUtil.getFileNameExtension(page.getDescPath()); File extensionFile = new File(extension[0]); if (!extensionFile.exists()) { extensionFile.mkdirs(); } bos = new BufferedOutputStream(new FileOutputStream(fileDesc)); int blen = 1024 * 5; byte[] b = new byte[blen]; int len = 0; while ((len = fis.read(b, 0, blen)) != -1) { bos.write(b, 0, len); } bos.flush(); log.debug("成功:保存网络文件地址:" + page.getDescPath()); } finally { if (bos != null) { try { bos.close(); } catch (Exception e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (Exception e) { e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (Exception e) { e.printStackTrace(); } } } } }
IDownload.java
package zjweb.download.pageModel; /** * 文件下载接口类<br> * * @version 1.00 (2011.12.02) * @author SHNKCS 张军 {@link <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>} */ public interface IDownload { /** * 下载文件后处理 * * @param page * 下载对象 * @author 张军 * @date 2015-11-03 21:59:00 * @modifiyNote * @version 1.0 */ void after(DownloadPage page); }
DownloadPage.java
package zjweb.download.pageModel; import java.io.Serializable; import lombok.Data; /** * 文件下载类<br> * * @version 1.00 (2011.12.02) * @author SHNKCS 张军 {@link <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a> <a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>} */ @Data public class DownloadPage implements Serializable { private static final long serialVersionUID = 1L; // private transient static final Logger log = Logger.getLogger(DownloadPage.class); /** 下载源文件地址 **/ private String srcPath; /** 目标文件地址 **/ private String descPath; /** 下载源文件重命名 **/ private String newFileName; /** 下载源文件重命名自动添加别名,默认不自动添加 **/ private boolean autoAddExtension; // 浏览器类型 private String userAgent; }
本文为张军原创文章,转载无需和我联系,但请注明来自张军的军军小站,个人博客http://www.zhangjunbk.com