import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public abstract class FileService {
/**
* filename 下载到客户端后的文件名称
* file 待下载的文件
* 下载 文件
*/
public void downloadFileToClient(String filename, File file, HttpServletResponse response) {
FileInputStream inStream = null;
try {
inStream = new FileInputStream(file);
byte[] buf = new byte[4096];
int readLength;
setResponseHeader(response, filename);
while (((readLength = inStream.read(buf)) != -1)) {
response.getOutputStream().write(buf, 0, readLength);
}
}catch (Exception e){
}finally {
try {
inStream.close();
} catch (Exception e) {
}
}
}
/**
* 设置响应头
* @param response
* @param fileName 文件名称
*/
protected void setResponseHeader(HttpServletResponse response, String fileName) {
String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
String prefix = fileName.substring(0, fileName.lastIndexOf("."));
try {
response.reset();
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(prefix.getBytes("GB2312"), "8859_1")
+ suffix);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
protected void downloadNetFile(String source, String dest) {
// 下载网络文件
// int bytesum = 0;
int byteread = 0;
InputStream inStream = null;
FileOutputStream fs = null;
try {
URL url = new URL(source);
URLConnection conn = url.openConnection();
inStream = conn.getInputStream();
fs = new FileOutputStream(dest);
byte[] buffer = new byte[inStream.available()];
// int length;
while ((byteread = inStream.read(buffer)) != -1) {
// bytesum += byteread;
fs.write(buffer, 0, byteread);
}
} catch (Exception e) {
} finally {
if (null != inStream) {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != fs) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}