網絡文件下載 下載文件-通過流 保存文件-網絡文件

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.dlhighland.cn">張軍個人網站</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.dlhighland.cn">張軍個人網站</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.dlhighland.cn">張軍個人網站</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.dlhighland.cn
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

