package com.huawei.download;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.http.Http
ServletResponse;
public class DownloadUtils
{
/**
*
* @param path 服务器目录下的文件路径
* @param response
* @return
*/
public static HttpServletResponse download(String path, HttpServletResponse response)
{
InputStream fis = null;
OutputStream toClient = null;
try
{
//需要下载的文件路径
File file = new File(path);
//取得
文件名
String filename = file.getName();
//以流的形式下载文件
fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
//将文件流中的数据读到字节数组中
fis.read(buffer);
//清空response
response.reset();
//设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
}
catch(IOException e)
{
throw new RuntimeException("IO流操作失败 " + e.toString());
}
finally
{
//统一关闭读写流
try
{
if(fis != null)
{
fis.close();
fis = null;
}
if(toClient != null)
{
toClient.close();
toClient = null;
}
}
catch(IOException e)
{
throw new RuntimeException("流关闭失败" + e.toString());
}
}
return response;
}
/**
* 通过URL下载网络文件
* @param localPath
* @param response
*/
public static void downloadByUrl(String localPath, HttpServletResponse response, URL url)
{
int bytesum = 0;
int byteread = 0;
URLConnection conn = null;
InputStream input = null;
OutputStream output = null;
try
{
conn = url.openConnection();
input = conn.getInputStream();
output = new FileOutputStream(localPath);
byte[] buffer = new byte[1024];
while((byteread = input.read(buffer)) != -1)
{
bytesum += byteread;
output.write(buffer, 0, byteread);
}
}
catch(MalformedURLException e)
{
throw new RuntimeException("URL
解析异常");
}
catch(IOException e)
{
throw new RuntimeException("IO流操作异常");
}
finally
{
try
{
if(input != null)
{
input.close();
input = null;
}
if(output != null)
{
output.close();
output = null;
}
}
catch(IOException e)
{
throw new RuntimeException("IO流关闭失败");
}
}
}
}