upload.js

<%@page import="java.net.URLEncoder"%>
<%@page import="java.net.URLDecoder"%>
<%@page import="java.io.UnsupportedEncodingException"%>
<%@page import="java.util.Enumeration"%>
<%@page import="com.sun.org.apache.regexp.internal.REUtil"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.*"%>
<%@page import="com.primeton.das.entity.impl.hibernate.mapping.Array"%>
<%@page import="com.eos.foundation.database.DatabaseUtil"%>
<%@page import="com.eos.data.datacontext.DataContextManager"%>
<%@page import="java.text.DecimalFormat"%>
<%@page import="com.eos.foundation.data.DataObjectUtil"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" session="false" %>
    
<%@page import="java.util.ArrayList"%>
<%@page import="commonj.sdo.DataObject"%>
<%@page import="java.util.Date"%>
<%@page import="java.util.Calendar"%>
<%@page import="java.io.File"%>
<%@page import="java.io.IOException"%>
<%@page import="java.util.List"%>
<%@page import="javax.servlet.http.HttpServletRequest"%>
<%@page import="javax.servlet.http.HttpServletResponse"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.FileUploadException"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>


<%@page import="com.primeton.eos.cwk_hyjys.dataset.LcFile"%>
<%@page import="java.sql.Timestamp"%>
<%@page import="com.eos.data.datacontext.DataContextManager"%>
        <%@page import="com.eos.data.datacontext.IUserObject"%>

<%!
    //List<DataObject> accessories = null;
    //String serverPath = null;
    String uploadStr = "";
    String encodeUrl(String path) {
        // 先處理%
        path = path.replace("%", "%25");
        path = path.replace("+", "%2B");
        path = path.replace(" ", "%20");
        path = path.replace("/", "%2F");
        path = path.replace("?", "%3F");
        path = path.replace("#", "%23");
        path = path.replace("&", "%26");
        path = path.replace("=", "%3D");
        
        return path;
    }
    String upload(HttpServletRequest request) {
        String serverPath = null;
        try {
            request.setCharacterEncoding("ISO-8859-1");
        }
        catch(UnsupportedEncodingException ex) {
        }
        String uploadDirName = "upload";
        String tempDirName = "temp";
        StringBuilder sBuilder = new StringBuilder();
        
        // 設置根目錄
        String webAppRealPath = request.getSession().getServletContext().getRealPath("/");
        
        // 獲取緩存目錄
        sBuilder.append(webAppRealPath).append(uploadDirName).append(File.separator);
        sBuilder.append(tempDirName);
        String tempFilePath = sBuilder.toString();
        
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        
        sBuilder.delete(0, sBuilder.length());
        sBuilder.append(webAppRealPath).append(uploadDirName).append(File.separator);
        sBuilder.append(calendar.get(Calendar.YEAR)).append("-");
        int month = calendar.get(Calendar.MONTH) + 1;
         int day = calendar.get(Calendar.DAY_OF_MONTH) ;
        sBuilder.append(month >= 10 ? month : "0" + month);
        String filePath = sBuilder.toString();
        
        // 要保存在數據庫中的路徑名稱
        String pathName =webAppRealPath+ File.separator + uploadDirName + File.separator +
            calendar.get(Calendar.YEAR) + "-" + (month >= 10 ? month : "0" + month);
            
            
            File tanSure=new File(webAppRealPath + uploadDirName + File.separator);
            System.out.println(webAppRealPath + uploadDirName + File.separator);
            if(!tanSure.exists()) {
               tanSure.mkdirs();
            }
            String lcm = request.getParameter("lcm"); 
            tanSure=new File(webAppRealPath+ uploadDirName + File.separator+lcm+File.separator);
            System.out.println(webAppRealPath + uploadDirName + File.separator+lcm+File.separator);
            if(!tanSure.exists()) {
               tanSure.mkdirs();
            }
            tanSure=new File(webAppRealPath + uploadDirName + File.separator+lcm+File.separator+calendar.get(Calendar.YEAR));
            System.out.println(webAppRealPath + uploadDirName + File.separator+lcm+File.separator+calendar.get(Calendar.YEAR));
            if(!tanSure.exists()) {
               tanSure.mkdirs();
            }
            tanSure=new File(webAppRealPath + uploadDirName + File.separator+lcm+File.separator+calendar.get(Calendar.YEAR)
            +File.separator+ (month >= 10 ? month : "0" + month));
            System.out.println(webAppRealPath + uploadDirName + File.separator+lcm+File.separator+calendar.get(Calendar.YEAR)
            +File.separator+ (month >= 10 ? month : "0" + month));
            if(!tanSure.exists()) {
               tanSure.mkdirs();
            }
             tanSure=new File(webAppRealPath + uploadDirName + File.separator+lcm+File.separator+calendar.get(Calendar.YEAR)
            +File.separator+ (month >= 10 ? month : "0" + month)+File.separator+day);
            System.out.println(webAppRealPath + uploadDirName + File.separator+lcm+File.separator+calendar.get(Calendar.YEAR)
            +File.separator+ (month >= 10 ? month : "0" + month)+File.separator+day);
            if(!tanSure.exists()) {
               tanSure.mkdirs();
            }
            
            pathName=webAppRealPath + uploadDirName + File.separator+lcm+File.separator+calendar.get(Calendar.YEAR)
            +File.separator+ (month >= 10 ? month : "0" + month)+File.separator+day;
            filePath=pathName;
            pathName= uploadDirName + File.separator+lcm+File.separator+calendar.get(Calendar.YEAR)
            +File.separator+ (month >= 10 ? month : "0" + month)+File.separator+day;
       
        File tempDir = new File(tempFilePath);
        //File uploadFileDir = new File(filePath);
        
        File uploadFileDir = new File(pathName);
        if(!tempDir.exists()) {
            tempDir.mkdirs();
        }
        if(!uploadFileDir.exists()) {
            uploadFileDir.mkdirs();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 設置內存緩衝區,超過後寫入臨時文件
        factory.setSizeThreshold(10240000);
        // 設置臨時文件存儲位置
        factory.setRepository(tempDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 設置單個文件的最大上傳值
        upload.setSizeMax(10002400000l);
        // 設置整個request的最大值
        upload.setSizeMax(10002400000l);
        upload.setHeaderEncoding("UTF-8");
        
        try {
            List<?> items = upload.parseRequest(request);
            FileItem item = null;
            String fileName = null;
            if(items == null) return "";
            //
            List<DataObject> accessories = new ArrayList<DataObject>();
            serverPath = "";
            for (int i = 0 ;i < items.size(); i++){
                item = (FileItem) items.get(i);
                
                if(item == null) continue;
                
                String uniqueName = getUniqueFileName(item.getName());
                fileName = filePath + File.separator + uniqueName;
                
                // 保存文件
                if (!item.isFormField() && item.getName().length() > 0) {
                    File fileToBeKept = new File(fileName);
                    item.write(fileToBeKept);
                    if(fileToBeKept != null && fileToBeKept.exists()) {
                       //
                        DataObject accessory = DataObjectUtil.createDataObject("com.primeton.eos.cwk_hyjys.dataset.LcFile");
                        pathName = pathName + File.separator + encodeUrl(uniqueName);
                        //System.out.println(pathName);
                        if("".equals(serverPath)){
                            serverPath = serverPath +pathName;
                        }else{
                            serverPath = serverPath+","+pathName;
                        }
                        //
                        accessory.setString("url", pathName);
                        System.out.println("originalname:"+item.getName());
                        accessory.setString("originalname", item.getName());                        
                        accessory.setLong("filesize", fileToBeKept.length());
                        accessory.setDate("uploadtime", new Timestamp(System.currentTimeMillis())  );
                        accessory.setString("filesizetext", FormetFileSize(fileToBeKept.length()));
     
 // accessory.setString("uploaduserid", DataContextManager.current().getMUODataContext().getUserObject().getUserId());
   //  accessory.setString("uploaduserName", com.primeton.cap.AppUserManager.getCurrentUserName());
   
  // System.out.println("uploaduserid:"+DataContextManager.current().getMUODataContext().getUserObject().getUserId());
   //     System.out.println("uploaduserName:"+com.primeton.cap.AppUserManager.getCurrentUserName());
     
    accessory.setString("uploaduserid", DataContextManager.current().getMUODataContext().getUserObject().getUserId());
   accessory.setString("uploadusername", com.primeton.cap.AppUserManager.getCurrentUserName());
 
       //accessory.setString("filesize", FormetFileSize(fileToBeKept.length()));
                        //String userId = request.getParameter("userId");
                        //String userName = request.getParameter("userName");
                        
                        //try {
                            //userName =  URLDecoder.decode(userName, "utf-8");
                            //System.out.println(request.getQueryString());
                            //System.out.println(userName);
                        //}
                        //catch(Exception ex) {}
                        /* String id = request.getParameter("id");
                        String operationId = request.getParameter("operationId");
                        String phototype = request.getParameter("phototype");
                        
                        accessory.setString("userid", userId);*/
                        /*
                         accessory.setString("username", userName);
                        if(id != null && !"undefined".equals(id)&& !"".equals(id)){
                            accessory.setString("id", id);
                        }
                        
                        accessory.setString("operationid", operationId);
                        accessory.setString("phototype", phototype);
                        accessory.setString("path", pathName);
                        accessory.setDate("createtime", new Date());
                        accessories.add(accessory);
                        String dsName = "default"; */
                        //saveAccessory(dsName,accessories);
                         accessories.add(accessory);
                      
                    }
                }
                
            }
            
            
            
              String dsName = "default"; 
             saveAccessory(dsName,accessories);
             
               System.out.println( "id:"+accessories.get(0).getString("id"));
               serverPath=serverPath.replaceAll("\\\\", "\\\\\\\\");
              serverPath= "{\"url\":\""+serverPath+"\",\"id\":\""+accessories.get(0).getString("id");
              serverPath= serverPath+"\",\"originalname\":\""+accessories.get(0).getString("originalname");
              
               serverPath= serverPath+"\",\"uploadusername\":\""+accessories.get(0).getString("uploadusername");
                
                
              serverPath= serverPath+"\",\"filesizetext\":\""+accessories.get(0).getString("filesizetext")+"\"}";
              
             System.out.println("size:"+accessories.size());
            
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverPath;
    }
    
    void saveAccessory(String dsName,List<DataObject> accessories) {
        DataObject[] arrayToSave = accessories.toArray(new DataObject[0]);
        if(arrayToSave != null) {
            DatabaseUtil.saveEntities(dsName, arrayToSave);
            System.out.println(arrayToSave.length);
        }
    }
    
    String FormetFileSize(long fileS) {//轉換文件大小
    
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }
    
    String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }
    String getFileExtension(String fileName) {
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            return "";
        }
    }
    String getUniqueFileName(String fileName) {
        
        if(fileName == null) return fileName;
        
        return getFileNameNoEx(fileName) + "_" + new Date().getTime() + "."
                + getFileExtension(fileName);
    }
 %>
<%
    
    String serverPath = upload(request);
    
    //保存到數據庫中:
  //  String dsName = "default"; 
  //  List<DataObject>  lists=new LinkedList<DataObject>();      
  //  DataObject accessory = DataObjectUtil.createDataObject("com.primeton.eos.cwk_hyjys.dataset.LcFile");

 // accessory.setLong("filesize", 1000L);
 //    accessory.setString("url", "test");
    // accessory.setString("uploaduserid", DataContextManager.current().getMUODataContext().getUserObject().getUserId());
   //  accessory.setString("uploaduserName", com.primeton.cap.AppUserManager.getCurrentUserName());
  //   accessory.setString("uploaduserid", "dd");
 //   accessory.setString("uploaduserName", "ddd");
    
   
   // accessory.setDate("uploadtime", new Date());
    // accessory.setDate("uploadtime", new Timestamp(System.currentTimeMillis())  );
     
    //  lists.add(accessory);
  //  saveAccessory(dsName,lists);

    
    //System.out.println("temp"+serverPath);
  //  uploadStr =uploadStr+","+ serverPath;
    System.out.println("serverPath:"+serverPath);
 //   System.out.println("uploadStr:"+uploadStr);
    response.getWriter().write(serverPath);    //可以返回一個JSON字符串, 在客戶端做更多處理
%>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章