|
@ -0,0 +1,76 @@
|
|
1
|
package com.ekexiu.portal.util;
|
|
2
|
|
|
3
|
import java.io.BufferedInputStream;
|
|
4
|
import java.io.BufferedOutputStream;
|
|
5
|
import java.io.File;
|
|
6
|
import java.io.FileInputStream;
|
|
7
|
import java.io.IOException;
|
|
8
|
import java.io.InputStream;
|
|
9
|
import java.io.OutputStream;
|
|
10
|
|
|
11
|
import javax.servlet.ServletException;
|
|
12
|
import javax.servlet.http.HttpServlet;
|
|
13
|
import javax.servlet.http.HttpServletRequest;
|
|
14
|
import javax.servlet.http.HttpServletResponse;
|
|
15
|
|
|
16
|
public class FileDownload extends HttpServlet {
|
|
17
|
private String accessoryFolder;
|
|
18
|
|
|
19
|
public String getAccessoryFolder() {
|
|
20
|
return accessoryFolder;
|
|
21
|
}
|
|
22
|
|
|
23
|
public void setAccessoryFolder(String accessoryFolder) {
|
|
24
|
this.accessoryFolder = accessoryFolder;
|
|
25
|
}
|
|
26
|
|
|
27
|
private static final long serialVersionUID = 1190786634322390349L;
|
|
28
|
|
|
29
|
/**
|
|
30
|
* 文件下载
|
|
31
|
*/
|
|
32
|
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
|
33
|
// 获取前台传回要下载的文件名
|
|
34
|
String fileName = request.getParameter("fileName");
|
|
35
|
// 获取下载文件的绝对路径path
|
|
36
|
String path = this.accessoryFolder + "/" + fileName;
|
|
37
|
try {
|
|
38
|
File file = new File(path);
|
|
39
|
// 取得文件名。
|
|
40
|
String filename = file.getName();
|
|
41
|
// 取得文件的后缀名。
|
|
42
|
// String ext = filename.substring(filename.lastIndexOf(".") +1).toUpperCase();
|
|
43
|
// 以流的形式下载文件。
|
|
44
|
InputStream fis = new BufferedInputStream(new FileInputStream(path));
|
|
45
|
byte[] buffer = new byte[fis.available()];
|
|
46
|
fis.read(buffer);
|
|
47
|
fis.close();
|
|
48
|
// 清空response
|
|
49
|
response.reset();
|
|
50
|
// 设置response的Header
|
|
51
|
response.addHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes("GB2312"),"iso8859-1"));
|
|
52
|
response.addHeader("Content-Length", "" + file.length());
|
|
53
|
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
|
|
54
|
// response.setContentType("application/octet-stream");
|
|
55
|
// 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
|
|
56
|
response.setContentType("multipart/form-data");
|
|
57
|
toClient.write(buffer);
|
|
58
|
toClient.flush();
|
|
59
|
toClient.close();
|
|
60
|
} catch (IOException ex) {
|
|
61
|
ex.printStackTrace();
|
|
62
|
}
|
|
63
|
}
|
|
64
|
|
|
65
|
public void doPost(HttpServletRequest request, HttpServletResponse response)
|
|
66
|
throws ServletException, IOException {
|
|
67
|
// TODO Auto-generated method stub
|
|
68
|
}
|
|
69
|
|
|
70
|
@Override
|
|
71
|
public void init() throws ServletException {
|
|
72
|
this.accessoryFolder = "D:/application/Workspaces/ekexiu.com.portal/src/main/webapp/accessory";
|
|
73
|
super.init();
|
|
74
|
}
|
|
75
|
|
|
76
|
}
|