1. 程式人生 > >通過URL下載文件

通過URL下載文件

return sch catch bis utf except 文件 路徑 final

URL url = new URL(fileRoute);//fileRoute:文件URL路徑
//通過URL的openStrean方法獲取URL對象所表示的自願字節輸入流
InputStream is = url.openStream();
// 設置response參數,可以打開下載頁面
response.reset();
String mimeType = MimeUtil.getMIMEType(fileName);//獲取Mime 類型列表 地址:http://www.w3school.com.cn/media/media_mimeref.asp

response.setContentType(""+mimeType+";charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("utf-8"), "ISO8859-1"));
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;

try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] e = new byte[2048];

int bytesRead;
while (-1 != (bytesRead = bis.read(e, 0, e.length))) {
bos.write(e, 0, bytesRead);
}
} catch (IOException arg24) {
throw arg24;
} finally {
if (bis != null) {
bis.close();
}

if (bos != null) {
bos.close();
}

}

return null;

通過URL下載文件