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, 02048);
          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, 01024);
          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 }
          posted on 2012-11-05 11:10 青城幻影 閱讀(11752) 評論(5)  編輯  收藏
          Comments
          • # e: 文件上傳下載rest實現
            彭少勇
            Posted @ 2013-04-11 17:48
            下載附件下載不了
              回復  更多評論   
          • # e: 文件上傳下載rest實現
            彭少勇
            Posted @ 2013-04-11 17:48
            附件下載不了  回復  更多評論   
          • # re: 文件上傳下載rest實現
            garca
            Posted @ 2014-06-16 14:14
            盡管學到了想要的東西,但是文檔里包含大量的業務內容,這種風格明顯是拷貝的的  回復  更多評論   
          • # re: 文件上傳下載rest實現
            韓少
            Posted @ 2014-09-25 17:00
            東西不錯  回復  更多評論   
          • # re: 文件上傳下載rest實現
            longer
            Posted @ 2015-08-05 14:15
            那些是Client上傳,哪些是Server端接收代碼啊?  回復  更多評論   

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
           
          主站蜘蛛池模板: 阿城市| 禹州市| 凉城县| 丹江口市| 鹤岗市| 九龙城区| 剑阁县| 鄱阳县| 怀柔区| 白山市| 泸州市| 嘉鱼县| 铜鼓县| 聊城市| 鹤山市| 南平市| 北海市| 五华县| 巴林右旗| 平湖市| 贵州省| 屏东市| 渭源县| 宜丰县| 新宾| 德昌县| 龙口市| 鄂温| 广饶县| 长武县| 当阳市| 东丰县| 平舆县| 东城区| 德江县| 姚安县| 英吉沙县| 望江县| 榕江县| 钦州市| 汕头市|