JAVA-IO 实现文件下载
InputStream in = null;
BufferedInputStream bIn = null;
BufferedOutputStream bOt = null;
ByteArrayOutputSream buf = null;
String filename = URLEncoder.encod(request.getParameter("filename"), "UTF-8");
String url = request.getParameter("url");
if(StringUtils.isNotEmpty(url)){
int startIndex = url.lastIndexOf(".");
String fix = url.substring(startIndex);
if(!filename.contains(fix)){
filename = filename + fix;
}
String userAgent = request.getHeader("User-Agent");
String fileName = filename.replace("+","");
try{
URL httpUrl = new URL(url);
URLConnection conn = httpUrl.openConnection();
in = conn.getInputStream();
bIn = new BufferedInputStream(in);
bOt = new BufferedOutputStream(response.getOutputStream());
response.setContentType("applicatino/octet-stream;charset=UTF-8");
response.setHeader("Content-disposition", StringUtils.contains(userAgent,"Firefox") ? ("attachment;filename*=utf-8''" + fileName) : ("attachment;filename=" + fileName));
buf = new ByteArrayOutputStream();
int result = bIn.read();
while(result != -1){
bOt.write(result);
result = bIn.read();
}
bOt.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
if(in != null){
in.close();
}
if(bIn != null){
bIn.close();
}
if(bOt != null){
bOt.close();
}
if(buf != null){
buf.close();
}
}
}
JAVA-NIO 实现文件下载
InputStream in = null;
BufferedOutputStream bOt = null;
ReadableByteChannel readChannel = null;
WritableByteChannel writeChannel = null;
String filename = URLEncoder.encod(request.getParameter("filename"), "UTF-8");
String url = request.getParameter("url");
if(StringUtils.isNotEmpty(url)){
int startIndex = url.lastIndexOf(".");
String fix = url.substring(startIndex);
if(!filename.contains(fix)){
filename = filename + fix;
}
String userAgent = request.getHeader("User-Agent");
String fileName = filename.replace("+","");
try{
URL httpUrl = new URL(url);
URLConnection conn = httpUrl.openConnection();
in = conn.getInputStream();
readChannel = Channels.newChannel(in);
bOt = new BufferedOutputStream(response.getOutputStream());
writeChannel = Channels.newChannel(bOt);
response.setContentType("applicatino/octet-stream;charset=UTF-8");
response.setHeader("Content-disposition", StringUtils.contains(userAgent,"Firefox") ? ("attachment;filename*=utf-8''" + fileName) : ("attachment;filename=" + fileName));
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(81920);
while(readChannel.read(byteBuffer) != -1) {
byteBuffer.flip();
while(byteBuffer.hasRemaining()){
writeChannel.write(byteBuffer);
}
byteBuffer.clear();
}
bOt.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
if(in != null){
in.close();
}
if(readChannel != null){
readChannel.close();
}
if(bOt != null){
bOt.close();
}
if(writeChannel != null){
writeChannel.close();
}
}
}