1 package com.augurit.agcom.rest;
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.FileNotFoundException;
8 import java.io.FileOutputStream;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import java.io.UnsupportedEncodingException;
13 import java.net.MalformedURLException;
14 import java.net.URL;
15 import java.text.SimpleDateFormat;
16 import java.util.ArrayList;
17 import java.util.Date;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21
22 import javax.servlet.ServletException;
23 import javax.servlet.http.HttpServletRequest;
24 import javax.servlet.http.HttpServletResponse;
25 import javax.ws.rs.Consumes;
26 import javax.ws.rs.GET;
27 import javax.ws.rs.POST;
28 import javax.ws.rs.Path;
29 import javax.ws.rs.PathParam;
30 import javax.ws.rs.Produces;
31 import javax.ws.rs.QueryParam;
32 import javax.ws.rs.core.Context;
33 import javax.ws.rs.core.MediaType;
34
35 import net.sf.json.JSONArray;
36 import net.sf.json.JSONObject;
37
38 import org.apache.commons.fileupload.FileItem;
39 import org.apache.commons.fileupload.FileItemFactory;
40 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
41 import org.apache.commons.fileupload.servlet.ServletFileUpload;
42 import org.apache.ibatis.ognl.Evaluation;
43 import org.apache.log4j.Logger;
44 import com.augurit.agcom.system.util.PropertiesReader;
45
46
47 import com.augurit.agcom.persistence.dao.IAgSupUploadfileDao;
48 import com.augurit.agcom.persistence.dao.impl.AgSupUploadfileDaoImpl;
49 import com.augurit.agcom.system.bean.AgSupUploadfile;
50 import com.augurit.agcom.system.bean.User;
51 import com.sun.jersey.api.spring.Autowire;
52 import com.sun.jersey.spi.resource.Singleton;
53
54
55
56 /**
57 * rest文件上传、下载服务 使用方法,/rest/uploadservices/(方法名)/(后面这些是方法的参数)
58 *
59 * @author Liuji
60 */
61 @Path("uploadservices")
62 @Singleton
63 @Autowire
64 public class FileUploadDownRest{
65
66 private IAgSupUploadfileDao agSupUploadfileDao=new AgSupUploadfileDaoImpl();
67
68 private static final Logger log = Logger.getLogger(FileUploadDownRest.class);
69
70 private static final String FILE_BELONG_OTHER="other"; //其他文件
71 private static final String FILE_BELONG_ZHOULH="zhoulh"; //周例会文件
72 /**
73 * 文件上传
74 * @param body
75 * @return
76 * @throws IOException
77 */
78 @POST
79 @Path("upload")
80 @Consumes( { MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
81 @Produces(MediaType.TEXT_PLAIN)
82 //@Produces("application/json")
83 public void upload( @Context HttpServletRequest request, @Context
84 HttpServletResponse response) throws IOException {
85 response.setCharacterEncoding("UTF-8");
86 String msg = "上传失败!";
87 Boolean flag=false;
88 Map<String, String> map= new HashMap<String, String>();
89 String objectNameStr = "";
90 String docbelongStr="";
91 String fileName="";
92 String fileFormat="";
93 String saveFilePath="";
94 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
95 if (isMultipart) {
96 // 构造一个文件上传处理对象
97 FileItemFactory factory = new DiskFileItemFactory();
98 ServletFileUpload upload = new ServletFileUpload(factory);
99 upload.setHeaderEncoding("utf-8"); // 支持中文文件名
100 List list = new ArrayList<FileItem>();
101 try {
102 // 解析表单中提交的所有文件内容
103 list = upload.parseRequest(request);
104 for (int i = 0; i < list.size(); i++) {
105 FileItem item = (FileItem) list.get(i);
106 if(item.isFormField()){ //普通表单值
107 map.put(item.getFieldName(), item.getString("UTF-8"));
108 }else {
109 String name = item.getName(); //获得上传的文件名(IE上是文件全路径,火狐等浏览器仅文件名)
110 fileName = name.substring(
111 name.lastIndexOf('\\') + 1, name.length());
112 fileFormat=fileName.substring(fileName.lastIndexOf(".")); //文件扩展名
113 objectNameStr = map.get("objectName"); //实体id
114 docbelongStr = map.get("docbelong"); //文件归属
115
116 //上传文件的保存的位置
117 // saveFilePath =PropertiesReader.getValue("agcom.fileupload.Path")+File.separator+objectNameStr;
118 saveFilePath=pathHandle(objectNameStr, docbelongStr);
119
120 // saveFilePath = request.getRealPath("/fileupload");
121 // absolutePath = projectLayerId+"/"+fileName;
122 // parseFile(item, filePath);
123 //上传操作
124 flag=upload4Stream(fileName, saveFilePath, item.getInputStream()); //上传文件
125 if(flag){
126 msg = "上传成功!";
127 }
128 }
129 }
130
131 AgSupUploadfile agSupUploadfile= new AgSupUploadfile();// 保存属性信息
132 User user = (User) request.getSession().getAttribute("user");
133 agSupUploadfile.setUserId(String.valueOf(user.getId()));
134 agSupUploadfile.setCmp(user.getUserName()); //上传人
135 agSupUploadfile.setCdt(getCurrentTime()); //上传时间
136 agSupUploadfile.setObjectName(map.get("objectName"));
137 agSupUploadfile.setFileFormat(fileFormat);
138 agSupUploadfile.setFilePath(saveFilePath);
139 agSupUploadfile.setFileName(fileName);
140 agSupUploadfile.setDocbelong(map.get("docbelong")); //上传文件归属
141 agSupUploadfile.setRemark(map.get("remark"));
142
143 agSupUploadfileDao.addAgSupUploadfile(agSupUploadfile);
144 } catch (Exception e) {
145 e.printStackTrace();
146 }
147 }
148 //msg="<html><body>"+msg+"<a href=\"javascript:window.history.back(-1);\">返回继续上传!</a>"+"</body></html>";
149 msg="<html><body>"+msg+"<input type=\"button\" value=\"返回继续上传\" onclick=\"window.history.back(-1);\"></body></html>";
150 //msg=msg+"<a href='javascript:window.history.back(-1);'>返回继续上传!</a>";
151 response.getWriter().write(msg);
152 // response.getWriter().write("<script language=javascript>+eval(alert("+msg+"));</script>");
153 // return "";
154 }
155
156 /**
157 * 上传文件解析(文件名处理、上传)
158 * @param item
159 * @param task
160 * @return
161 */
162 private boolean parseFile(FileItem item, String filePath) throws Exception {
163 boolean flag = false;
164 try {
165 // 上传文件的上传路径
166 String name = item.getName();
167 // 上传文件的文件名
168 String fileName = name.substring(name.lastIndexOf('\\') + 1, name
169 .length());
170 if (fileName == null) {
171 String[] str = fileName.split(".");
172 if (str != null && str.length == 2)
173 fileName = str[0] + (new Date()).getTime() + str[1];
174 }
175 flag = this
176 .upload4Stream(fileName, filePath, item.getInputStream());
177 } catch (Exception e) {
178 e.printStackTrace();
179 }
180 return flag;
181 }
182
183 /**
184 * 上传文件具体操作
185 * @param fileName 文件名
186 * @param filePath 文件上传路径
187 * @param inStream 文件流
188 * @return 上传是否成功
189 */
190 private boolean upload4Stream(String fileName, String filePath,
191 InputStream inStream) {
192 boolean result = false;
193 if ((filePath == null) || (filePath.trim().length() == 0)) {
194 return result;
195 }
196 OutputStream outStream = null;
197 try {
198 String wholeFilePath = filePath + "\\" + fileName;
199 File dir = new File(filePath);
200 if (!dir.exists()) {
201 dir.mkdirs();
202 }
203 File outputFile = new File(wholeFilePath);
204 boolean isFileExist = outputFile.exists();
205 boolean canUpload = true;
206 if (isFileExist) {
207 canUpload = outputFile.delete();
208 }
209 if (canUpload) {
210 int available = 0;
211 outStream = new BufferedOutputStream(new FileOutputStream(
212 outputFile), 2048);
213 byte[] buffer = new byte[2048];
214 while ((available = inStream.read(buffer)) > 0) {
215 if (available < 2048)
216 outStream.write(buffer, 0, available);
217 else {
218 outStream.write(buffer, 0, 2048);
219 }
220 }
221 result = true;
222 }
223 } catch (Exception e) {
224 e.printStackTrace();
225 try {
226 if (inStream != null) {
227 inStream.close();
228 }
229 if (outStream != null)
230 outStream.close();
231 } catch (Exception ex) {
232 e.printStackTrace();
233 }
234 } finally {
235 try {
236 if (inStream != null) {
237 inStream.close();
238 }
239 if (outStream != null)
240 outStream.close();
241 } catch (Exception e) {
242 e.printStackTrace();
243 }
244 }
245 return result;
246 }
247
248 /**
249 * 文件下载
250 * @throws UnsupportedEncodingException
251 * @throws IOException
252 */
253 @GET
254 @Path("/download")
255 @Produces(MediaType.TEXT_PLAIN)
256 public String downloadFile(@Context HttpServletRequest request, @Context HttpServletResponse response,
257 @QueryParam("fileName")String fileName, @QueryParam("objectName")String objectName,
258 @QueryParam("docbelong")String docbelong) throws UnsupportedEncodingException {
259 response.setContentType("text/html; charset=UTF-8");
260 response.setCharacterEncoding("UTF-8");
261 Boolean isOnLine = false; //是否在线浏览
262 //得到下载文件的名字
263 String fileNameStr = java.net.URLDecoder.decode(fileName, "utf-8");
264 //解决中文乱码问题
265 // String filename=new String(request.getParameter("filename").getBytes("iso-8859-1"),"gbk");
266
267 StringBuffer path=new StringBuffer(pathHandle(objectName, docbelong))
268 .append(File.separator).append(fileNameStr);
269 File file = new File(path.toString());
270 FileInputStream fis = null;
271 BufferedInputStream buff = null;
272 OutputStream myout = null;
273 try {
274 if (!file.exists()) {
275 response.sendError(404, "File not found!");
276 return "";
277 }
278 response.reset();
279 if (isOnLine) { //在线打开方式
280 URL u = new URL("file:///" + path.toString());
281 response.setContentType(u.openConnection().getContentType());
282 response.setHeader("Content-Disposition", "inline; filename="
283 + new String(file.getName().getBytes("gbk"), "iso-8859-1"));
284 } else { //纯下载方式
285 //设置response的编码方式
286 response.setContentType("application/x-msdownload");
287 //写明要下载的文件的大小
288 response.setContentLength((int) file.length());
289 //设置附加文件名(解决中文乱码)
290 response.setHeader("Content-Disposition",
291 "attachment;filename=" + new String(file.getName().getBytes("gbk"), "iso-8859-1"));
292 }
293
294 fis = new FileInputStream(file);
295 buff = new BufferedInputStream(fis);
296 byte[] b = new byte[1024];//相当于我们的缓存
297 long k = 0;//该值用于计算当前实际下载了多少字节
298 //从response对象中得到输出流,准备下载
299 myout = response.getOutputStream();
300 while (k < file.length()) {
301 int j = buff.read(b, 0, 1024);
302 k += j;
303 //将b中的数据写到客户端的内存
304 myout.write(b, 0, j);
305 }
306 //将写入到客户端的内存的数据,刷新到磁盘
307 myout.flush();
308 } catch (MalformedURLException e) {
309 // TODO Auto-generated catch block
310 e.printStackTrace();
311 } catch (FileNotFoundException e) {
312 // TODO Auto-generated catch block
313 e.printStackTrace();
314 } catch (IOException e) {
315 // TODO Auto-generated catch block
316 e.printStackTrace();
317 } finally {
318 try {
319 if (fis != null) {
320 fis.close();
321 }
322 if (buff != null)
323 buff.close();
324 if (myout != null)
325 myout.close();
326 } catch (Exception e) {
327 e.printStackTrace();
328 }
329 }
330
331 return "";
332 }
333
334 private String getCurrentTime() {
335 Date currentTime = new Date();
336 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
337 String dateString = formatter.format(currentTime);
338 return dateString;
339 }
340
341 /*文件路径处理
342 * 返回路径如:C\:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\upload\\10\\other
343 */
344 private String pathHandle(String objectName,String docbelong) {
345
346 StringBuffer path = new StringBuffer(PropertiesReader
347 .getValue("agcom.fileupload.Path"));
348 path.append(File.separator).append(objectName).append(File.separator);
349
350 if ("0".equals(docbelong)) { // 其他文件
351 path.append(FileUploadDownRest.FILE_BELONG_OTHER);
352 } else if ("1".equals(docbelong)) { // 周例会文件
353 path.append(FileUploadDownRest.FILE_BELONG_ZHOULH);
354 }
355 return path.toString();
356 }
357 /**
358 * 获取文件列表
359 * @param request
360 * @param response
361 * @param docbelong 文件归属
362 * @param objectName
363 * @throws IOException
364 * @throws ServletException
365 * 请求路径如:http://localhost:8089/agcom/rest/uploadservices/filelist/0?objectName='10'
366 */
367 @GET
368 @Path("/filelist/{docbelong}")
369 @Produces("application/json")
370 public String getFileList(@Context HttpServletRequest request, @Context HttpServletResponse response,
371 @PathParam("docbelong")String docbelong, @QueryParam("objectName")String objectName) throws ServletException, IOException{
372 response.setContentType("text/html");
373 response.setCharacterEncoding("UTF-8");
374 Map<String,String> map=new HashMap<String, String>();
375 map.put("docbelong",docbelong);
376 map.put("objectName",objectName);
377 //根据objectName查询 关联的文件集合
378 IAgSupUploadfileDao agSupUploadfileDao=new AgSupUploadfileDaoImpl();
379 List<AgSupUploadfile> agSupUploadfiles=agSupUploadfileDao.selectByMoreParam(map);
380 JSONArray array=JSONArray.fromObject(agSupUploadfiles); //json对象数组
381 String arrayStr=array.toString();
382 return arrayStr;
383 }
384 }