Exemple #1
0
 public void upload() throws Exception {
   boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
   if (!isMultipart) {
     this.state = this.errorInfo.get("NOFILE");
     return;
   }
   DiskFileItemFactory dff = new DiskFileItemFactory();
   String savePath = this.getFolder(this.savePath);
   dff.setRepository(new File(savePath));
   try {
     ServletFileUpload sfu = new ServletFileUpload(dff);
     sfu.setSizeMax(this.maxSize * 1024);
     sfu.setHeaderEncoding("utf-8");
     FileItemIterator fii = sfu.getItemIterator(this.request);
     while (fii.hasNext()) {
       FileItemStream fis = fii.next();
       if (!fis.isFormField()) {
         this.originalName =
             fis.getName()
                 .substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
         if (!this.checkFileType(this.originalName)) {
           this.state = this.errorInfo.get("TYPE");
           continue;
         }
         this.fileName = this.getName(this.originalName);
         this.type = this.getFileExt(this.fileName);
         this.url = savePath + "/" + this.fileName;
         BufferedInputStream in = new BufferedInputStream(fis.openStream());
         FileOutputStream out = new FileOutputStream(new File(this.getPhysicalPath(this.url)));
         BufferedOutputStream output = new BufferedOutputStream(out);
         Streams.copy(in, output, true);
         this.state = this.errorInfo.get("SUCCESS");
         // UE中只会处理单张上传,完成后即退出
         break;
       } else {
         String fname = fis.getFieldName();
         // 只处理title,其余表单请自行处理
         if (!fname.equals("pictitle")) {
           continue;
         }
         BufferedInputStream in = new BufferedInputStream(fis.openStream());
         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
         StringBuffer result = new StringBuffer();
         while (reader.ready()) {
           result.append((char) reader.read());
         }
         this.title = new String(result.toString().getBytes(), "utf-8");
         reader.close();
       }
     }
   } catch (SizeLimitExceededException e) {
     this.state = this.errorInfo.get("SIZE");
   } catch (InvalidContentTypeException e) {
     this.state = this.errorInfo.get("ENTYPE");
   } catch (FileUploadException e) {
     this.state = this.errorInfo.get("REQUEST");
   } catch (Exception e) {
     this.state = this.errorInfo.get("UNKNOWN");
   }
 }
  /**
   * @param request
   * @throws UnsupportedEncodingException
   */
  public void parseRequest(HttpServletRequest request) throws UnsupportedEncodingException {

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setSizeThreshold(sizeThreshold);

    if (repository != null) factory.setRepository(repository);

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setHeaderEncoding(encoding);

    try {
      List<FileItem> items = upload.parseRequest(request);

      for (FileItem item : items) {
        if (item.isFormField()) {
          String fieldName = item.getFieldName();
          String value = item.getString(encoding);
          parameters.put(fieldName, value);
        } else {

          if (!super.isValidFile(item)) {
            continue;
          }

          if (fileItem == null) fileItem = item;
        }
      }

    } catch (FileUploadException e) {
      e.printStackTrace();
    }
  }
Exemple #3
0
  private void parseParams() {

    DiskFileItemFactory dff = new DiskFileItemFactory();
    try {
      ServletFileUpload sfu = new ServletFileUpload(dff);
      sfu.setSizeMax(this.maxSize);
      sfu.setHeaderEncoding(Uploader.ENCODEING);

      FileItemIterator fii = sfu.getItemIterator(this.request);

      while (fii.hasNext()) {
        FileItemStream item = fii.next();
        // 普通参数存储
        if (item.isFormField()) {

          this.params.put(item.getFieldName(), this.getParameterValue(item.openStream()));

        } else {

          // 只保留一个
          if (this.inputStream == null) {
            this.inputStream = item.openStream();
            this.originalName = item.getName();
            return;
          }
        }
      }

    } catch (Exception e) {
      this.state = this.errorInfo.get("UNKNOWN");
    }
  }
  public MultipartFormBean getFileFromRequest(HttpServletRequest request)
      throws FileUploadException {
    try {
      if (encoding != null) request.setCharacterEncoding(encoding);
    } catch (UnsupportedEncodingException e1) {
      throw new FileUploadException("Upload file encoding not supported!");
    }

    MultipartFormBean resultBean = new MultipartFormBean();

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding(encoding);
    upload.setFileSizeMax(maxSize);
    List items = upload.parseRequest(request);

    Map fields = new HashMap();
    try {
      Iterator iter = items.iterator();
      while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
          // parameter values check
          String fn = item.getFieldName();
          if (fn.startsWith("l_")) {
            if (fields.keySet().contains(fn)) {
              String[] arr = (String[]) fields.get(fn);
              String[] newArr = new String[arr.length + 1];
              for (int i = 0; i < arr.length; i++) newArr[i] = arr[i];
              newArr[arr.length] = item.getString();
              fields.put(fn, newArr);
            } else {
              fields.put(fn, new String[] {item.getString(encoding)});
            }
          } else {
            fields.put(fn, item.getString(encoding));
          }
        } else {
          String ext = getFileExt(item.getName());
          if (ext == null) {
            fields.put(item.getFieldName(), null);
            continue;
          }
          if (!extIsAllowed(ext)) {
            throw new FileUploadException("Upload file format '" + ext + "' is not accepted!");
          }
          resultBean.addFileItem(item);
          fields.put(item.getFieldName(), null);
        }
      }

      resultBean.setFields(fields);
    } catch (UnsupportedEncodingException e) {
      throw new FileUploadException("Upload file encoding not supported!");
    }

    return resultBean;
  }
Exemple #5
0
  @SuppressWarnings("unchecked")
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    log.info("upload start------");
    request.setCharacterEncoding("UTF-8");
    StringBuffer savePath = new StringBuffer("/mnt/web/static/images/album/");
    Calendar c = Calendar.getInstance();
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd/");
    String date = df.format(c.getTime());
    savePath.append(date);
    File dir = new File(savePath.toString());
    if (!dir.exists()) {
      dir.mkdirs();
    }
    DiskFileItemFactory fac = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(fac);
    upload.setHeaderEncoding("UTF-8");
    List<FileItem> list = null;
    try {
      list = upload.parseRequest(request);
    } catch (FileUploadException e) {
      log.error(e.getMessage(), e);
      return;
    }
    log.info("file size:{}", list.size());
    for (FileItem it : list) {
      if (!it.isFormField()) {
        String name = it.getName();
        long size = it.getSize();
        String type = it.getContentType();
        log.info("name:{},size:{},type:{}", name, size, type);
        if (StringUtils.isBlank(name)) {
          continue;
        }
        String extName = null;
        if (name.lastIndexOf(".") >= 0) {
          extName = name.substring(name.lastIndexOf("."));
        }
        File file = null;
        do {
          name = UUIDUtil.getRandomUUID();
          file = new File(savePath + name + extName);
        } while (file.exists());
        File saveFile = new File(savePath + name + extName);
        log.info("path:{}", saveFile.getAbsolutePath());
        try {
          it.write(saveFile);
          albumService.newPhoto(1, saveFile.getAbsolutePath(), "none");
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    response.getWriter().write("1");
    log.info("upload end------");
  }
Exemple #6
0
 /**
  * Utility method for parsing a multipart servlet request. This method returns an iterator of
  * FileItem objects that corresponds to the request.
  *
  * @param request The servlet request containing the multipart request.
  * @return Returns an iterator of FileItem objects the corresponds to the request.
  * @throws Exception Thrown if any problems occur while processing the request.
  */
 protected static Iterator processMultipartRequest(HttpServletRequest request) throws Exception {
   // Create a factory for disk-based file items
   DiskFileItemFactory factory = new DiskFileItemFactory();
   factory.setRepository(new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH)));
   ServletFileUpload upload = new ServletFileUpload(factory);
   upload.setHeaderEncoding("UTF-8");
   upload.setSizeMax(Environment.getLongValue(Environment.PROP_FILE_MAX_FILE_SIZE));
   return upload.parseRequest(request).iterator();
 }
Exemple #7
0
  private String getFile(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    // 如果是文件上传类型
    StringBuffer fileStr = new StringBuffer();
    //		PrintWriter out = resp.getWriter();
    if (ServletFileUpload.isMultipartContent(req)) {
      // 得到文件上传工厂
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setSizeThreshold(5000 * 1024);
      factory.setRepository(new File("c:/temp"));

      // 处理文件上传核心类
      ServletFileUpload fileUpload = new ServletFileUpload(factory);
      fileUpload.setFileSizeMax(50000 * 1024);
      // 设置文件上传类的编码格式
      fileUpload.setHeaderEncoding("UTF-8");
      // 集合数据 : FileItem对象 注意: 每一个表单域 对应一个 FileItem对象(封装)

      try {
        List<FileItem> fileItemList = fileUpload.parseRequest(req);
        for (FileItem item : fileItemList) {
          // 如果这个文本域是文件类型的
          if (!item.isFormField()) {
            CustomLog.info(item.getFieldName());
            InputStream inputStream = item.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);

            int tempbyte;
            while ((tempbyte = bis.read()) != -1) {
              char c = (char) tempbyte;
              System.out.write(tempbyte);
              fileStr.append(c);
            }

          } else {
            //                           CustomLog.info(item.getFieldName());
            //                           CustomLog.info(item.getString());
          }
        }
      } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return fileStr.toString();
  }
Exemple #8
0
 public XLReader(HttpServletRequest request) throws IOException {
   parameters = new HashMap<String, String>();
   try {
     byte[] file = null;
     ServletFileUpload upload = new ServletFileUpload(getDiskFileItemFactory());
     upload.setHeaderEncoding("utf-8");
     List<FileItem> items = upload.parseRequest(request);
     Iterator<FileItem> iter = items.iterator();
     while (iter.hasNext()) {
       FileItem item = iter.next();
       if (item.isFormField()) {
         parameters.put(item.getFieldName(), item.getString());
       } else {
         file = item.get();
       }
     }
     workbooks.add(new HSSFWorkbook(new POIFSFileSystem(new ByteArrayInputStream(file))));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  private void doParse() {
    String tmpPath = ConfigFacade.getValue("tmpFile.path");
    String encoding = ConfigFacade.getValue("http.encoding");

    File tmpDir = new File(tmpPath);
    boolean success = false;

    try {
      if (!tmpDir.exists()) {
        tmpDir.mkdirs();
        success = true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (!success) {
      tmpPath = System.getProperty("java.io.tmpdir");
      tmpDir = new File(tmpPath);
    }

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory(100 * 1024, tmpDir));
    upload.setHeaderEncoding(encoding);
    try {
      List<FileItem> items = upload.parseRequest(req);
      for (Iterator iter = items.iterator(); iter.hasNext(); ) {
        FileItem item = (FileItem) iter.next();
        if (!item.isFormField()) {
          fileItems.add(item);
        } else {
          parameters.put(item.getFieldName(), item.getString(encoding));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.info("error parse request");
    }
  }
Exemple #10
0
 @SuppressWarnings("all")
 public static boolean process(HttpServletRequest request) {
   if (!ServletFileUpload.isMultipartContent(request)) {
     return false;
   }
   upload.setHeaderEncoding("utf-8");
   try {
     List<FileItem> formItems = upload.parseRequest(request);
     if (formItems != null && formItems.size() > 0) {
       for (FileItem item : formItems) {
         if (!item.isFormField()) {
           request.setAttribute("_file_", item.get());
           request.setAttribute("_file_name_", item.getName());
         } else {
           request.setAttribute(item.getFieldName(), new String(item.get()));
         }
       }
     }
   } catch (Exception ex) {
     EasywebLogger.error("[FileUpload] Error", ex);
   }
   return true;
 }
Exemple #11
0
  @SuppressWarnings("unchecked")
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    Integer schunk = null; // 分割块数
    Integer schunks = null; // 总分割数
    String name = null; // 文件名
    BufferedOutputStream outputStream = null;
    if (ServletFileUpload.isMultipartContent(request)) {
      try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        factory.setRepository(new File(repositoryPath)); // 设置临时目录
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        upload.setSizeMax(5 * 1024 * 1024); // 设置附近大小
        List<FileItem> items = upload.parseRequest(request);
        // 生成新文件名
        String newFileName = null;
        for (FileItem item : items) {
          if (!item.isFormField()) { // 如果是文件类型
            name = item.getName(); // 获得文件名
            newFileName =
                UUID.randomUUID()
                    .toString()
                    .replace("-", "")
                    .concat(".")
                    .concat(FilenameUtils.getExtension(name));
            if (name != null) {
              String nFname = newFileName;
              if (schunk != null) {
                nFname = schunk + "_" + name;
              }
              File savedFile = new File(uploadPath, nFname);
              item.write(savedFile);
            }
          } else {
            // 判断是否带分割信息
            if (item.getFieldName().equals("chunk")) {
              schunk = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("chunks")) {
              schunks = Integer.parseInt(item.getString());
            }
          }
        }

        if (schunk != null && schunk + 1 == schunks) {
          outputStream =
              new BufferedOutputStream(new FileOutputStream(new File(uploadPath, newFileName)));
          // 遍历文件合并
          for (int i = 0; i < schunks; i++) {
            File tempFile = new File(uploadPath, i + "_" + name);
            byte[] bytes = FileUtils.readFileToByteArray(tempFile);
            outputStream.write(bytes);
            outputStream.flush();
            tempFile.delete();
          }
          outputStream.flush();
        }
        response.getWriter().write("{\"status\":true,\"newName\":\"" + newFileName + "\"}");
      } catch (FileUploadException e) {
        e.printStackTrace();
        response.getWriter().write("{\"status\":false}");
      } catch (Exception e) {
        e.printStackTrace();
        response.getWriter().write("{\"status\":false}");
      } finally {
        try {
          if (outputStream != null) outputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  /**
   * 上传宠物头像
   *
   * @param request
   * @param response
   * @throws IOException
   */
  @RequestMapping(value = "/uploadavatar")
  public void uploadPetAvatar(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

    upload.setHeaderEncoding("UTF-8");

    List<FileItem> items;
    String userName = "";
    String petId = "";
    IdBean petUpdateReturnBean = new IdBean();
    try {
      items = upload.parseRequest(request);
      log.info("items : " + items);
      if (items == null) {
        throw new FileUploadException();
      }

      FileItem file2Upload = null;
      for (FileItem item : items) {
        log.info("field name: " + item.getFieldName());
        if ("avatar_file".equals(item.getFieldName())) {
          file2Upload = item;
        } else if ("petid".equals(item.getFieldName())) {
          petId = item.getString();
        } else if ("username".equals(item.getFieldName())) {
          userName = item.getString();
        }
      }
      if (file2Upload == null) {
        throw new FileUploadException("No avatar file");
      }

      String avatarFileName = UUID.randomUUID().toString();
      // save avatar file
      FileUtil.saveFile(avatarFileName, file2Upload);

      if (StringUtil.isNullOrEmpty(petId)) {
        if (!petInfoDao.hasPetInfo(userName)) {
          // create new avatar
          long id = petInfoDao.createPetAvatarInfo(avatarFileName, userName);
          log.info("create pet id: " + id);
          if (id > 0) {
            petUpdateReturnBean.setResult("0");
            petUpdateReturnBean.setId(String.valueOf(id));
          } else {
            petUpdateReturnBean.setResult("4");
          }
        } else {
          petUpdateReturnBean.setResult("3"); // already has pet
        }
      } else {
        // update avatar
        // String avatar = petInfoDao.getPetAvatar(petId);
        // if (!StringUtil.isNullOrEmpty(avatar)) {
        // avatarFileName = avatar;
        // }
        int update = petInfoDao.updatePetAvatar(petId, avatarFileName);
        if (update > 0) {
          petUpdateReturnBean.setResult("0");
          petUpdateReturnBean.setId(petId);
        } else {
          petUpdateReturnBean.setResult("1"); // update failed
        }
      }
    } catch (FileUploadException e) {
      e.printStackTrace();
      petUpdateReturnBean.setResult("2"); // no file
    } catch (Exception e) {
      e.printStackTrace();
      petUpdateReturnBean.setResult("5"); // save file failed
    }
    response.getWriter().print(JSONUtil.toString(petUpdateReturnBean));
  }
Exemple #13
0
  @EipkRequest(value = "/s/article/upload", method = RequestMethod.POST, ajax = true)
  public AjaxData articleUploadFile(Model m) {
    Map<String, Object> result = new HashMap<String, Object>();

    String savePath = m.getRequest().getServletContext().getRealPath("/upload/");
    File saveDirFile = new File(savePath);
    if (!saveDirFile.exists()) {
      saveDirFile.mkdirs();
    }
    FileItemFactory fac = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(fac);
    upload.setHeaderEncoding("utf-8");

    List<?> fileList = null;
    try {
      fileList = upload.parseRequest(m.getRequest());
    } catch (FileUploadException e) {
      e.printStackTrace();
      return null;
    }
    Iterator<?> par_itr = fileList.iterator(), file_itr = fileList.iterator();
    while (par_itr.hasNext()) {
      FileItem item = (FileItem) par_itr.next();
      if (item.isFormField()) {
        try {
          String par_name = item.getFieldName();
          BufferedReader br;
          br = new BufferedReader(new InputStreamReader(item.getInputStream()));
          if (par_name != null) {
            result.put(par_name, br.readLine());
          }
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    while (file_itr.hasNext()) {
      FileItem item = (FileItem) file_itr.next();
      String fileName = item.getName();
      if (!item.isFormField()) {
        try {
          int index = fileName.lastIndexOf("\\");
          if (index != -1) {
            fileName = fileName.substring(index + 1);
          }
          result.put("fileName", fileName);
          result.put("fileType", fileName.substring(fileName.lastIndexOf(".") + 1));
          String file_disk_name = java.util.UUID.randomUUID().toString();
          fileName = file_disk_name + fileName.substring(fileName.lastIndexOf("."));
          File uploadedFile = new File(savePath, fileName);
          item.write(uploadedFile);
          result.put("fileSize", SysUtil.FileSizeStr(item.getSize()));
          result.put("fileDiskName", file_disk_name);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    DB db = new DB();
    String sql = "insert into t_file (fileName,fileDiskName,fileSize,fileType) values (?,?,?,?)";
    int file_id =
        db.execute(
            sql,
            result.get("fileName"),
            result.get("fileDiskName"),
            result.get("fileSize"),
            result.get("fileType"));
    sql = "insert into t_appendix (articleId,fileId) values (?,?)";
    db.execute(sql, SysUtil.StrToInt("" + result.get("article_id")), file_id);
    db.close();

    return new AjaxData(result);
  }
Exemple #14
0
  @SuppressWarnings({"rawtypes", "rawtypes", "unchecked"})
  @None
  public String uploadFile(HttpServletRequest req, HttpServletResponse resp) {
    String savePath =
        req.getSession().getServletContext().getRealPath("/") + UploadTool.TEAM_SAVE_DIR_NAME + "/";
    String saveUrl = req.getContextPath() + "/" + UploadTool.TEAM_SAVE_DIR_NAME + "/";
    String[] fileTypes = UploadTool.TEAM_SUFFIXS;
    long maxSize = UploadTool.TEAM_MAX_SIZE;

    String fileExt = "";
    resp.setContentType("text/html; charset=UTF-8");
    PrintWriter out = null;
    try {
      out = resp.getWriter();
    } catch (IOException e1) {
      log.error("获取PrintWriter对象发生异常", e1.getCause());
      return NONE;
    }
    if (!ServletFileUpload.isMultipartContent(req)) {
      out.println(UploadTool.getErrorJson("请选择文件"));
      return NONE;
    }
    File uploadDir = new File(savePath);
    if (!uploadDir.exists()) uploadDir.mkdir();
    if (!uploadDir.isDirectory()) {
      out.println(UploadTool.getErrorJson("上传目录不存在"));
      return NONE;
    }
    if (!uploadDir.canWrite()) {
      out.println(UploadTool.getErrorJson("上传目录没有写权限"));
      return NONE;
    }
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    List items = null;
    try {
      items = upload.parseRequest(req);
    } catch (FileUploadException e1) {
      log.error("解析请求对象发生异常", e1.getCause());
      out.println(UploadTool.getErrorJson("获取文件异常"));
      return NONE;
    }
    Iterator itr = items.iterator();
    while (itr.hasNext()) {
      FileItem item = (FileItem) itr.next();
      String fileName = item.getName();
      if (!item.isFormField()) {
        if (item.getSize() > maxSize) {
          out.println(UploadTool.getErrorJson("上传文件大小超过限制,最大为[" + maxSize + "]"));
          return NONE;
        }
        fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String>asList(fileTypes).contains(fileExt)) {
          out.println(UploadTool.getErrorJson("上传文件扩展名是不允许的扩展名"));
          return NONE;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName =
            df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        try {
          File uploadedFile = new File(savePath, newFileName);
          item.write(uploadedFile);
        } catch (Exception e) {
          out.println(UploadTool.getErrorJson("上传文件失败"));
          return NONE;
        }
        JSONObject obj = new JSONObject();
        obj.put("error", 0);
        obj.put("url", saveUrl + newFileName);
        out.println(obj.toJSONString());
        log.info("Upload headimage Successful , Headimage path -> " + saveUrl + newFileName);
      }
    }
    return NONE;
  }
Exemple #15
0
  public static final State save(HttpServletRequest request, Map<String, Object> conf) {
    FileItemStream fileStream = null;
    boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;

    if (!ServletFileUpload.isMultipartContent(request)) {
      return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
    }

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

    if (isAjaxUpload) {
      upload.setHeaderEncoding("UTF-8");
    }

    try {
      FileItemIterator iterator = upload.getItemIterator(request);

      while (iterator.hasNext()) {
        fileStream = iterator.next();

        if (!fileStream.isFormField()) break;
        fileStream = null;
      }

      if (fileStream == null) {
        return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
      }

      String savePath = (String) conf.get("savePath");
      String originFileName = fileStream.getName();
      String suffix = FileType.getSuffixByFilename(originFileName);

      originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
      savePath = savePath + suffix;

      long maxSize = ((Long) conf.get("maxSize")).longValue();

      if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
        return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
      }

      savePath = PathFormat.parse(savePath, originFileName);

      String physicalPath = (String) conf.get("rootPath") + savePath;

      InputStream is = fileStream.openStream();
      State storageState = StorageManager.saveFileByInputStream(is, physicalPath, maxSize);
      is.close();

      if (storageState.isSuccess()) {
        storageState.putInfo("url", PathFormat.format(savePath));
        storageState.putInfo("type", suffix);
        storageState.putInfo("original", originFileName + suffix);
      }

      return storageState;
    } catch (FileUploadException e) {
      return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
    } catch (IOException e) {
    }
    return new BaseState(false, AppInfo.IO_ERROR);
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    // 文件保存目录路径
    String savePath = req.getServletContext().getRealPath("/") + "attached/";

    // 文件保存目录URL
    String saveUrl = req.getContextPath() + "/attached/";

    // 定义允许上传的文件扩展名
    HashMap<String, String> extMap = new HashMap<String, String>();
    extMap.put("image", "gif,jpg,jpeg,png,bmp");
    extMap.put("flash", "swf,flv");
    extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
    extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

    // 最大文件大小
    long maxSize = 1000000;

    resp.setContentType("text/html; charset=UTF-8");

    if (!ServletFileUpload.isMultipartContent(req)) {
      resp.getWriter().println(getError("请选择文件。"));
      return;
    }
    // 检查目录
    File uploadDir = new File(savePath);
    if (!uploadDir.isDirectory()) {
      resp.getWriter().println(getError("上传目录不存在。"));
      return;
    }
    // 检查目录写权限
    if (!uploadDir.canWrite()) {
      resp.getWriter().println(getError("上传目录没有写权限。"));
      return;
    }

    String dirName = req.getParameter("dir");
    if (dirName == null) {
      dirName = "image";
    }
    if (!extMap.containsKey(dirName)) {
      resp.getWriter().println(getError("目录名不正确。"));
      return;
    }
    // 创建文件夹
    savePath += dirName + "/";
    saveUrl += dirName + "/";
    File saveDirFile = new File(savePath);
    if (!saveDirFile.exists()) {
      saveDirFile.mkdirs();
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String ymd = sdf.format(new Date());
    savePath += ymd + "/";
    saveUrl += ymd + "/";
    File dirFile = new File(savePath);
    if (!dirFile.exists()) {
      dirFile.mkdirs();
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    try {
      List<FileItem> items = upload.parseRequest(req);
      Iterator itr = items.iterator();
      while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        String fileName = item.getName();
        long fileSize = item.getSize();
        if (!item.isFormField()) {
          if (item.getName() != null && !item.getName().equals("")) {
            // 检查文件大小
            if (item.getSize() > maxSize) {
              resp.getWriter().println(getError("上传文件大小超过限制。"));
              return;
            }
            // 检查扩展名
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
              resp.getWriter()
                  .println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
              return;
            }

            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName =
                df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
            try {
              File uploadedFile = new File(savePath, newFileName);
              item.write(uploadedFile);
            } catch (Exception e) {
              resp.getWriter().println(getError("上传文件失败。"));
              return;
            }

            JSONObject obj = new JSONObject();
            obj.put("error", 0);
            obj.put("url", saveUrl + newFileName);
            resp.getWriter().println(obj.toJSONString());
          } else {
            resp.getWriter().println(getError("没有选择文件"));
            return;
          }
        }
      }
    } catch (FileUploadException e1) {
      resp.getWriter().println(getError("FileUploadException"));
      return;
    }
  }
  /**
   * Utility method to decode a multipart/fomr-data stream and return a Map of parameters of type
   * Object[], each of which can be a String or FileData.
   */
  public static Map<String, Object[]> getParameterMapMultipart(
      PipelineContext pipelineContext,
      final ExternalContext.Request request,
      String headerEncoding) {

    final Map<String, Object[]> uploadParameterMap = new HashMap<String, Object[]>();
    try {
      // Setup commons upload

      // Read properties
      // NOTE: We use properties scoped in the Request generator for historical reasons. Not too
      // good.
      int maxSize = RequestGenerator.getMaxSizeProperty();
      int maxMemorySize = RequestGenerator.getMaxMemorySizeProperty();

      final DiskFileItemFactory diskFileItemFactory =
          new DiskFileItemFactory(maxMemorySize, SystemUtils.getTemporaryDirectory());

      final ServletFileUpload upload =
          new ServletFileUpload(diskFileItemFactory) {
            protected FileItem createItem(Map headers, boolean isFormField)
                throws FileUploadException {
              if (isFormField) {
                // Handle externalized values
                final String externalizeFormValuesPrefix =
                    org.orbeon.oxf.properties.Properties.instance()
                        .getPropertySet()
                        .getString(ServletExternalContext.EXTERNALIZE_FORM_VALUES_PREFIX_PROPERTY);
                final String fieldName = getFieldName(headers);
                if (externalizeFormValuesPrefix != null
                    && fieldName.startsWith(externalizeFormValuesPrefix)) {
                  // In this case, we do as if the value content is an uploaded file so that it can
                  // be externalized
                  return super.createItem(headers, false);
                } else {
                  // Just create the FileItem using the default way
                  return super.createItem(headers, isFormField);
                }
              } else {
                // Just create the FileItem using the default way
                return super.createItem(headers, isFormField);
              }
            }
          };
      upload.setHeaderEncoding(headerEncoding);
      upload.setSizeMax(maxSize);

      // Add a listener to destroy file items when the pipeline context is destroyed
      pipelineContext.addContextListener(
          new PipelineContext.ContextListenerAdapter() {
            public void contextDestroyed(boolean success) {
              for (final String name : uploadParameterMap.keySet()) {
                final Object values[] = uploadParameterMap.get(name);
                for (final Object currentValue : values) {
                  if (currentValue instanceof FileItem) {
                    final FileItem fileItem = (FileItem) currentValue;
                    fileItem.delete();
                  }
                }
              }
            }
          });

      // Wrap and implement just the required methods for the upload code
      final InputStream inputStream;
      try {
        inputStream = request.getInputStream();
      } catch (IOException e) {
        throw new OXFException(e);
      }

      final RequestContext requestContext =
          new RequestContext() {

            public int getContentLength() {
              return request.getContentLength();
            }

            public InputStream getInputStream() {
              // NOTE: The upload code does not actually check that it doesn't read more than the
              // content-length
              // sent by the client! Maybe here would be a good place to put an interceptor and make
              // sure we
              // don't read too much.
              return new InputStream() {
                public int read() throws IOException {
                  return inputStream.read();
                }
              };
            }

            public String getContentType() {
              return request.getContentType();
            }

            public String getCharacterEncoding() {
              return request.getCharacterEncoding();
            }
          };

      // Parse the request and add file information
      try {
        for (Object o : upload.parseRequest(requestContext)) {
          final FileItem fileItem = (FileItem) o;
          // Add value to existing values if any
          if (fileItem.isFormField()) {
            // Simple form field
            // Assume that form fields are in UTF-8. Can they have another encoding? If so, how is
            // it specified?
            StringUtils.addValueToObjectArrayMap(
                uploadParameterMap,
                fileItem.getFieldName(),
                fileItem.getString(STANDARD_PARAMETER_ENCODING));
          } else {
            // File
            StringUtils.addValueToObjectArrayMap(
                uploadParameterMap, fileItem.getFieldName(), fileItem);
          }
        }
      } catch (FileUploadBase.SizeLimitExceededException e) {
        // Should we do something smart so we can use the Presentation
        // Server error page anyway? Right now, this is going to fail
        // miserably with an error.
        throw e;
      } catch (UnsupportedEncodingException e) {
        // Should not happen
        throw new OXFException(e);
      } finally {
        // Close the input stream; if we don't nobody does, and if this stream is
        // associated with a temporary file, that file may resist deletion
        if (inputStream != null) {
          try {
            inputStream.close();
          } catch (IOException e) {
            throw new OXFException(e);
          }
        }
      }

      return uploadParameterMap;
    } catch (FileUploadException e) {
      throw new OXFException(e);
    }
  }
  /**
   * The doPost method of the servlet. <br>
   * This method is called when a form has its tag value method equals to post.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String originalName = "";
    String savePath = this.getServletConfig().getServletContext().getRealPath("/");
    savePath = savePath + "/Accessory/";
    File f1 = new File(savePath);
    if (!f1.exists()) {
      f1.mkdirs();
    }
    DiskFileItemFactory fac = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(fac);
    upload.setHeaderEncoding("utf-8");
    List fileList = null;
    try {
      fileList = upload.parseRequest(request);
    } catch (FileUploadException ex) {
      return;
    }

    Iterator<FileItem> it = fileList.iterator();
    String name = "";
    String extName = "";
    while (it.hasNext()) {
      FileItem item = it.next();
      if (!item.isFormField()) {
        name = item.getName();
        long size = item.getSize();
        String type = item.getContentType();
        System.out.println(size + " " + type);
        if (name == null || name.trim().equals("")) {
          continue;
        }

        // 扩展名格式:
        if (name.lastIndexOf(".") >= 0) {
          extName = name.substring(name.lastIndexOf("."));
        }
        originalName = name;
        File file = null;
        do {
          // 生成文件名:
          name = UUID.randomUUID().toString();
          file = new File(savePath + name + extName);
        } while (file.exists());
        File saveFile = new File(savePath + name + extName);
        try {
          item.write(saveFile);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    JSONObject json = new JSONObject();
    json.put("address", "Accessory/" + name + extName);
    json.put("filename", originalName);
    out.print(name + extName);
    out.flush();
    out.close();
  }
  @SuppressWarnings("unchecked")
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    log.debug("doPost({}, {})", request, response);
    String fileName = null;
    InputStream is = null;
    String path = null;
    int action = 0;
    long size = 0;
    boolean notify = false;
    boolean importZip = false;
    boolean autoCheckOut = false;
    String users = null;
    String roles = null;
    String message = null;
    String comment = null;
    String folder = null;
    String rename = null;
    PrintWriter out = null;
    String uploadedUuid = null;
    java.io.File tmp = null;
    boolean redirect = false;
    boolean convertToPdf = false;
    String redirectURL = "";
    updateSessionManager(request);

    // JSON Stuff
    Ref<FileUploadResponse> fuResponse = new Ref<FileUploadResponse>(new FileUploadResponse());

    try {
      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType(MimeTypeConfig.MIME_TEXT);
      out = response.getWriter();
      log.debug("isMultipart: {}", isMultipart);

      // Create a factory for disk-based file items
      if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String contentLength = request.getHeader("Content-Length");
        FileUploadListener listener = new FileUploadListener(Long.parseLong(contentLength));

        // Saving listener to session
        request.getSession().setAttribute(FILE_UPLOAD_STATUS, listener);
        upload.setHeaderEncoding("UTF-8");

        // upload servlet allows to set upload listener
        upload.setProgressListener(listener);
        List<FileItem> items = upload.parseRequest(request);

        // Parse the request and get all parameters and the uploaded file
        for (Iterator<FileItem> it = items.iterator(); it.hasNext(); ) {
          FileItem item = it.next();

          if (item.isFormField()) {
            if (item.getFieldName().equals("path")) {
              path = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("action")) {
              action = Integer.parseInt(item.getString("UTF-8"));
            }

            if (item.getFieldName().equals("users")) {
              users = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("roles")) {
              roles = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("notify")) {
              notify = true;
            }

            if (item.getFieldName().equals("importZip")) {
              importZip = true;
            }

            if (item.getFieldName().equals("autoCheckOut")) {
              autoCheckOut = true;
            }

            if (item.getFieldName().equals("message")) {
              message = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("comment")) {
              comment = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("folder")) {
              folder = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("rename")) {
              rename = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("redirect")) {
              redirect = true;
              redirectURL = item.getString("UTF-8");
            }

            if (item.getFieldName().equals("convertToPdf")) {
              convertToPdf = true;
            }
          } else {
            fileName = item.getName();
            is = item.getInputStream();
            size = item.getSize();
          }
        }

        // Save document with different name than uploaded
        log.debug("Filename: '{}'", fileName);
        if (rename != null && !rename.equals("")) {
          log.debug("Rename: '{}'", rename);

          if (FilenameUtils.indexOfExtension(rename) > -1) {
            // The rename contains filename + extension
            fileName = rename;
          } else {
            // The rename only contains filename, so get extension from uploaded file
            String ext = FilenameUtils.getExtension(fileName);

            if (ext.equals("")) {
              fileName = rename;
            } else {
              fileName = rename + "." + ext;
            }
          }

          log.debug("Filename: '{}'", fileName);
        }

        // Now, we have read all parameters and the uploaded file
        if (action == UIFileUploadConstants.ACTION_INSERT) {
          if (fileName != null && !fileName.equals("")) {
            if (importZip && FilenameUtils.getExtension(fileName).equalsIgnoreCase("zip")) {
              log.debug("Import ZIP file '{}' into '{}'", fileName, path);
              String erroMsg = importZip(path, is);

              if (erroMsg == null) {
                sendResponse(out, action, fuResponse.get());
              } else {
                log.warn("erroMsg: {}", erroMsg);
                fuResponse.get().setError(erroMsg);
                sendResponse(out, action, fuResponse.get());
              }
            } else if (importZip && FilenameUtils.getExtension(fileName).equalsIgnoreCase("jar")) {
              log.debug("Import JAR file '{}' into '{}'", fileName, path);
              String erroMsg = importJar(path, is);

              if (erroMsg == null) {
                sendResponse(out, action, fuResponse.get());
              } else {
                fuResponse.get().setError(erroMsg);
                sendResponse(out, action, fuResponse.get());
              }
            } else if (FilenameUtils.getExtension(fileName).equalsIgnoreCase("eml")) {
              log.debug("import EML file '{}' into '{}'", fileName, path);
              String erroMsg = importEml(path, is);

              if (erroMsg == null) {
                sendResponse(out, action, fuResponse.get());
              } else {
                log.warn("erroMsg: {}", erroMsg);
                fuResponse.get().setError(erroMsg);
                sendResponse(out, action, fuResponse.get());
              }
            } else if (FilenameUtils.getExtension(fileName).equalsIgnoreCase("msg")) {
              log.debug("import MSG file '{}' into '{}'", fileName, path);
              String erroMsg = importMsg(path, is);

              if (erroMsg == null) {
                sendResponse(out, action, fuResponse.get());
              } else {
                log.warn("erroMsg: {}", erroMsg);
                fuResponse.get().setError(erroMsg);
                sendResponse(out, action, fuResponse.get());
              }
            } else {
              fileName = FilenameUtils.getName(fileName);
              log.debug(
                  "Upload file '{}' into '{} ({})'",
                  new Object[] {fileName, path, FormatUtil.formatSize(size)});
              String mimeType = MimeTypeConfig.mimeTypes.getContentType(fileName.toLowerCase());
              Document doc = new Document();
              doc.setPath(path + "/" + fileName);

              if (convertToPdf && !mimeType.equals(MimeTypeConfig.MIME_PDF)) {
                DocConverter converter = DocConverter.getInstance();

                if (converter.convertibleToPdf(mimeType)) {
                  // Changing path name
                  if (fileName.contains(".")) {
                    fileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "pdf";
                  } else {
                    fileName += ".pdf";
                  }

                  doc.setPath(path + "/" + fileName);
                  tmp = File.createTempFile("okm", ".tmp");
                  java.io.File tmpPdf = File.createTempFile("okm", ".pdf");
                  FileOutputStream fos = new FileOutputStream(tmp);
                  IOUtils.copy(is, fos);
                  converter.doc2pdf(tmp, mimeType, tmpPdf);
                  is = new FileInputStream(tmpPdf);
                  doc = OKMDocument.getInstance().create(null, doc, is);
                  fuResponse.get().setPath(doc.getPath());
                  uploadedUuid = doc.getUuid();
                  tmp.delete();
                  tmpPdf.delete();
                  tmp = null;
                } else {
                  throw new ConversionException("Not convertible to pdf");
                }
              } else {
                log.debug("Wizard: {}", fuResponse);

                if (Config.REPOSITORY_NATIVE) {
                  doc = new DbDocumentModule().create(null, doc, is, size, null, fuResponse);
                  fuResponse.get().setPath(doc.getPath());
                  uploadedUuid = doc.getUuid();
                } else {
                  doc = new JcrDocumentModule().create(null, doc, is);
                  fuResponse.get().setPath(doc.getPath());
                  uploadedUuid = doc.getUuid();
                }

                log.debug("Wizard: {}", fuResponse);
              }

              // Return the path of the inserted document in response
              sendResponse(out, action, fuResponse.get());
            }
          }
        } else if (action == UIFileUploadConstants.ACTION_UPDATE) {
          log.debug("File updated: {}", path);

          // http://en.wikipedia.org/wiki/Truth_table#Applications => ¬p ∨ q
          if (!Config.SYSTEM_DOCUMENT_NAME_MISMATCH_CHECK
              || PathUtils.getName(path).equals(fileName)) {
            Document doc = OKMDocument.getInstance().getProperties(null, path);

            if (autoCheckOut) {
              // This is set from the Uploader applet
              OKMDocument.getInstance().checkout(null, path);
            }

            if (Config.REPOSITORY_NATIVE) {
              new DbDocumentModule().checkin(null, path, is, size, comment, null);
              fuResponse.get().setPath(path);
              uploadedUuid = doc.getUuid();
            } else {
              new JcrDocumentModule().checkin(null, path, is, comment);
              fuResponse.get().setPath(path);
              uploadedUuid = doc.getUuid();
            }

            // Return the path of the inserted document in response
            sendResponse(out, action, fuResponse.get());
          } else {
            fuResponse
                .get()
                .setError(
                    ErrorCode.get(
                        ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_DocumentNameMismatch));
            sendResponse(out, action, fuResponse.get());
          }
        } else if (action == UIFileUploadConstants.ACTION_FOLDER) {
          log.debug("Folder create: {}", path);
          Folder fld = new Folder();
          fld.setPath(path + "/" + folder);
          fld = OKMFolder.getInstance().create(null, fld);
          fuResponse.get().setPath(fld.getPath());
          sendResponse(out, action, fuResponse.get());
        }

        listener.setUploadFinish(true); // Mark uploading operation has finished

        // If the document have been added to the repository, perform user notification
        if ((action == UIFileUploadConstants.ACTION_INSERT
                || action == UIFileUploadConstants.ACTION_UPDATE)
            & notify) {
          List<String> userNames =
              new ArrayList<String>(
                  Arrays.asList(users.isEmpty() ? new String[0] : users.split(",")));
          List<String> roleNames =
              new ArrayList<String>(
                  Arrays.asList(roles.isEmpty() ? new String[0] : roles.split(",")));

          for (String role : roleNames) {
            List<String> usersInRole = OKMAuth.getInstance().getUsersByRole(null, role);

            for (String user : usersInRole) {
              if (!userNames.contains(user)) {
                userNames.add(user);
              }
            }
          }

          String notifyPath = URLDecoder.decode(fuResponse.get().getPath(), "UTF-8");
          OKMNotification.getInstance().notify(null, notifyPath, userNames, message, false);
        }

        // After uploading redirects to some URL
        if (redirect) {
          ServletContext sc = getServletContext();
          request.setAttribute("docPath", fuResponse.get().getPath());
          request.setAttribute("uuid", uploadedUuid);
          sc.setAttribute("docPath", fuResponse.get().getPath());
          sc.setAttribute("uuid", uploadedUuid);
          sc.getRequestDispatcher(redirectURL).forward(request, response);
        }
      }
    } catch (AccessDeniedException e) {
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_AccessDenied));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (PathNotFoundException e) {
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_PathNotFound));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (ItemExistsException e) {
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_ItemExists));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (UnsupportedMimeTypeException e) {
      fuResponse
          .get()
          .setError(
              ErrorCode.get(
                  ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_UnsupportedMimeType));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (FileSizeExceededException e) {
      fuResponse
          .get()
          .setError(
              ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_FileSizeExceeded));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (LockException e) {
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Lock));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (VirusDetectedException e) {
      fuResponse
          .get()
          .setError(VirusDetectedException.class.getSimpleName() + " : " + e.getMessage());
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (VersionException e) {
      log.error(e.getMessage(), e);
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Version));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (RepositoryException e) {
      log.error(e.getMessage(), e);
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Repository));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (DatabaseException e) {
      log.error(e.getMessage(), e);
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Database));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (ExtensionException e) {
      log.error(e.getMessage(), e);
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Extension));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (IOException e) {
      log.error(e.getMessage(), e);
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_IO));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (ConversionException e) {
      fuResponse
          .get()
          .setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Conversion));
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      fuResponse.get().setError(e.toString());
      sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
    } finally {
      if (tmp != null) {
        tmp.delete();
      }

      IOUtils.closeQuietly(is);
      out.flush();
      IOUtils.closeQuietly(out);
      System.gc();
    }
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=utf-8");

    // 设置存储位置
    String upload = this.getServletContext().getRealPath("/upload");
    String temp = this.getServletContext().getRealPath("/temp");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024 * 5); // 100k--进入缓存的入口大小
    factory.setRepository(new File(temp));

    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    fileUpload.setHeaderEncoding("UTF-8");
    fileUpload.setFileSizeMax(1024 * 1024 * 3); //
    fileUpload.setSizeMax(1024 * 1024 * 5);
    System.out.println("upload:" + upload);
    // 5、检查是否为正确的表单上传方式---enctype="multipart/form-data"
    if (!ServletFileUpload.isMultipartContent(request)) {
      throw new RuntimeException("请使用正确的表单提交方式");
    }
    try {
      List<FileItem> list = fileUpload.parseRequest(request);

      for (FileItem fileItem : list) {
        if (fileItem.isFormField()) {
          // 字段
        } else {
          // 文件
          String name = fileItem.getName();
          String strUUID = UUID.randomUUID().toString();
          if (name.endsWith(".jpg") || name.endsWith(".png") || name.endsWith(".gif")) {
            strUUID += "_picture" + name.substring(name.lastIndexOf("."));

            // 设置文件输出流
            try {
              InputStream is = fileItem.getInputStream(); // 获取文件流
              OutputStream os = new FileOutputStream(new File(upload, strUUID));
              // 将文件存储到服务器响应位置
              IOUtils.In2Out(is, os);
              IOUtils.close(is, os);
              // 删除temp中缓存的文件
              fileItem.delete();

              // 将图片信息存储到数据库
            } catch (Exception e) {
              e.printStackTrace();
              throw new RuntimeException("输出流异常");
            }
          }
        }
      }
    } catch (FileSizeLimitExceededException e) {
      System.out.println("file size is not allowed");
    } catch (FileUploadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    response.getWriter().append("Served at: ").append(request.getContextPath());
  }
  /**
   * if the filter is configured to parse file uploads, AND the request is multipart (typically a
   * file upload), then parse the request.
   *
   * @return If there is a file upload, and the filter handles it, return the wrapped request that
   *     has the results of the parsed file upload. Parses the files using Apache
   *     commons-fileuplaod. Exposes the results through a wrapped request. Files are available
   *     like: fileItem = (FileItem) request.getAttribute("myHtmlFileUploadId");
   */
  protected HttpServletRequest handleFileUpload(
      HttpServletRequest req, HttpServletResponse resp, List<FileItem> tempFiles)
      throws ServletException, UnsupportedEncodingException {
    if (!m_uploadEnabled
        || !ServletFileUpload.isMultipartContent(req)
        || req.getAttribute(ATTR_UPLOADS_DONE) != null) {
      return req;
    }

    // mark that the uploads have been parsed, so they aren't parsed again on this request
    req.setAttribute(ATTR_UPLOADS_DONE, ATTR_UPLOADS_DONE);

    // Result - map that will be created of request parameters,
    // parsed parameters, and uploaded files
    Map map = new HashMap();

    // parse using commons-fileupload

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // set the factory parameters: the temp dir and the keep-in-memory-if-smaller threshold
    if (m_uploadTempDir != null) factory.setRepository(new File(m_uploadTempDir));
    if (m_uploadThreshold > 0) factory.setSizeThreshold(m_uploadThreshold);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // set the encoding
    String encoding = req.getCharacterEncoding();
    if (encoding != null && encoding.length() > 0) upload.setHeaderEncoding(encoding);

    // set the max upload size
    long uploadMax = -1;
    if (m_uploadMaxSize > 0) uploadMax = m_uploadMaxSize;

    // check for request-scoped override to upload.max (value in megs)
    String override = req.getParameter(CONFIG_UPLOAD_MAX);
    if (override != null) {
      try {
        // get the max in bytes
        uploadMax = Long.parseLong(override) * 1024L * 1024L;
      } catch (NumberFormatException e) {
        M_log.warn(CONFIG_UPLOAD_MAX + " set to non-numeric: " + override);
      }
    }

    // limit to the ceiling
    if (uploadMax > m_uploadCeiling) {
      M_log.warn(
          "Upload size exceeds ceiling: "
              + ((uploadMax / 1024L) / 1024L)
              + " > "
              + ((m_uploadCeiling / 1024L) / 1024L)
              + " megs");

      uploadMax = m_uploadCeiling;
    }

    // to let commons-fileupload throw the exception on over-max, and also halt full processing of
    // input fields
    if (!m_uploadContinue) {
      // TODO: when we switch to commons-fileupload 1.2
      // // either per file or overall request, as configured
      // if (m_uploadMaxPerFile)
      // {
      // upload.setFileSizeMax(uploadMax);
      // }
      // else
      // {
      // upload.setSizeMax(uploadMax);
      // }

      upload.setSizeMax(uploadMax);
    }

    try {
      // parse multipart encoded parameters
      boolean uploadOk = true;
      List list = upload.parseRequest(req);
      for (int i = 0; i < list.size(); i++) {
        FileItem item = (FileItem) list.get(i);

        if (item.isFormField()) {
          String str = item.getString(encoding);

          Object obj = map.get(item.getFieldName());
          if (obj == null) {
            map.put(item.getFieldName(), new String[] {str});
          } else if (obj instanceof String[]) {
            String[] old_vals = (String[]) obj;
            String[] values = new String[old_vals.length + 1];
            for (int i1 = 0; i1 < old_vals.length; i1++) {
              values[i1] = old_vals[i1];
            }
            values[values.length - 1] = str;
            map.put(item.getFieldName(), values);
          } else if (obj instanceof String) {
            String[] values = new String[2];
            values[0] = (String) obj;
            values[1] = str;
            map.put(item.getFieldName(), values);
          }
        } else {
          // collect it for delete at the end of the request
          tempFiles.add(item);

          // check the max, unless we are letting commons-fileupload throw exception on max exceeded
          // Note: the continue option assumes the max is per-file, not overall.
          if (m_uploadContinue && (item.getSize() > uploadMax)) {
            uploadOk = false;

            M_log.info("Upload size limit exceeded: " + ((uploadMax / 1024L) / 1024L));

            req.setAttribute("upload.status", "size_limit_exceeded");
            // TODO: for 1.2 commons-fileupload, switch this to a FileSizeLimitExceededException
            req.setAttribute(
                "upload.exception",
                new FileUploadBase.SizeLimitExceededException("", item.getSize(), uploadMax));
            req.setAttribute("upload.limit", new Long((uploadMax / 1024L) / 1024L));
          } else {
            req.setAttribute(item.getFieldName(), item);
          }
        }
      }

      // unless we had an upload file that exceeded max, set the upload status to "ok"
      if (uploadOk) {
        req.setAttribute("upload.status", "ok");
      }
    } catch (FileUploadBase.SizeLimitExceededException ex) {
      M_log.info("Upload size limit exceeded: " + ((upload.getSizeMax() / 1024L) / 1024L));

      // DON'T throw an exception, instead note the exception
      // so that the tool down-the-line can handle the problem
      req.setAttribute("upload.status", "size_limit_exceeded");
      req.setAttribute("upload.exception", ex);
      req.setAttribute("upload.limit", new Long((upload.getSizeMax() / 1024L) / 1024L));
    }
    // TODO: put in for commons-fileupload 1.2
    // catch (FileUploadBase.FileSizeLimitExceededException ex)
    // {
    // M_log.info("Upload size limit exceeded: " + ((upload.getFileSizeMax() / 1024L) / 1024L));
    //
    // // DON'T throw an exception, instead note the exception
    // // so that the tool down-the-line can handle the problem
    // req.setAttribute("upload.status", "size_limit_exceeded");
    // req.setAttribute("upload.exception", ex);
    // req.setAttribute("upload.limit", new Long((upload.getFileSizeMax() / 1024L) / 1024L));
    // }
    catch (FileUploadException ex) {
      M_log.info("Unexpected exception in upload parsing", ex);
      req.setAttribute("upload.status", "exception");
      req.setAttribute("upload.exception", ex);
    }

    // add any parameters that were in the URL - make sure to get multiples
    for (Enumeration e = req.getParameterNames(); e.hasMoreElements(); ) {
      String name = (String) e.nextElement();
      String[] values = req.getParameterValues(name);
      map.put(name, values);
    }

    // return a wrapped response that exposes the parsed parameters and files
    return new WrappedRequestFileUpload(req, map);
  }
Exemple #22
0
  public static byte[] getFileBytes(HttpServletRequest request) {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // 不做迁移
    // 获得磁盘文件条目工厂
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // 获取文件需要上传到的路径

    // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
    factory.setSizeThreshold(1024 * 1024);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    try {
      // 可以上传多个文件
      List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

      for (FileItem item : list) {
        // 获取表单的属性名字
        String name = item.getFieldName();

        // 如果获取的 表单信息是普通的 文本 信息
        if (item.isFormField()) {
          // 获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
          String value = new String(item.getString().getBytes("iso-8859-1"), "utf-8");

          request.setAttribute(name, value);
        } // 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
        else {
          /** 以下三步,主要获取 上传文件的名字 */
          // 获取路径名
          String value = item.getName();
          // 这里访问数据库
          // 索引到最后一个反斜杠
          value = java.net.URLDecoder.decode(value, "UTF-8");
          int start = value.lastIndexOf("\\");
          // 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
          String filename = value.substring(start + 1);

          InputStream in = item.getInputStream();
          int length = 0;
          byte[] buf = new byte[1024];
          System.out.println("获取上传文件的总共的容量:" + item.getSize());
          // in.read(buf) 每次读到的数据存放在 buf 数组中
          while ((length = in.read(buf)) != -1) {
            // 在 buf 数组中 取出数据 写到 (输出流)磁盘上
            out.write(buf, 0, length);
          }

          try {

            if (in != null) {
              in.close();
            }

          } catch (IOException ex) {
            Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
          }
          return out.toByteArray();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      try {
        out.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, e);
      }
    }
    return null;
  }
  /**
   * 接收文件数据。
   *
   * @param name
   * @param request
   */
  public void receive(String name, HttpServletRequest request) {
    ServletFileUpload upload = new ServletFileUpload(this.factory);
    upload.setSizeMax(this.fileSizeMax);
    upload.setHeaderEncoding("UTF-8");

    // 设置文件上传进度监听器
    FileProgressListener pl = new FileProgressListener(name, request.getSession());
    upload.setProgressListener(pl);

    try {
      List<FileItem> items = upload.parseRequest(request);

      for (FileItem item : items) {
        if (!item.isFormField()) {
          // 原始文件名
          String originFileName = item.getName();

          // 文件后缀名
          String extension = FileUtils.extractFileExtension(originFileName);

          // 文件别名
          String aliasFileName = Utils.randomString(32) + "." + extension;

          FileType fileType = FileType.parseType(extension);

          if (FileType.UNKNOWN != fileType) {
            // 存储路径
            String strFilePath = this.storePath + name + "/";

            // 创建工作目录
            File filePath = new File(this.workPath + name + "/");
            if (!filePath.exists()) {
              filePath.mkdirs();
            }
            // 创建存储目录
            filePath = new File(strFilePath);
            if (!filePath.exists()) {
              filePath.mkdirs();
            }
            filePath = null;

            // 删除相同文件
            SharedFile sf = this.existSharedFile(originFileName);
            if (null != sf) {
              sf.delete();
              this.removeSharedFile(sf);
            }

            // 原文件
            File originFile = new File(strFilePath, originFileName);
            // 别名文件
            File aliasFile = new File(this.workPath + name + "/", aliasFileName);

            sf = new SharedFile(name, originFile, aliasFile, fileType, request.getSession());

            // 添加分享文件
            this.addSharedFile(sf);

            synchronized (pl.files) {
              pl.files.add(sf);
            }

            // 写文件
            item.write(originFile);

            request.getSession().setAttribute("name", name);
            request.getSession().setAttribute("filename", originFileName);
          } else {
            // 不支持的类型
            Logger.w(this.getClass(), "不支持的文件类型: " + originFileName);

            request.getSession().setAttribute("name", name);
            request.getSession().setAttribute("filename", originFileName);
            request.getSession().setAttribute("state", 300);
          }
        }
      }

      // 结束
      pl.finish();
    } catch (FileUploadException e) {
      Logger.log(this.getClass(), e, LogLevel.ERROR);
    } catch (Exception e) {
      Logger.log(this.getClass(), e, LogLevel.ERROR);
    }
  }
Exemple #24
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String saveFilename = null;
    String realSavePath = null;
    String filename = null;

    Users users = (Users) request.getSession().getAttribute("loginuser");
    int sid = users.getIdusers();

    // 得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
    String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
    // 上传时生成的临时文件保存目录
    String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
    File tmpFile = new File(tempPath);
    if (!tmpFile.exists()) {
      // 创建临时目录
      tmpFile.mkdir();
    }

    // 消息提示
    String message = "";
    try {
      // 使用Apache文件上传组件处理文件上传步骤:
      // 1、创建一个DiskFileItemFactory工厂
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // 设置工厂的缓冲区的大小,当上传的文件大小超过缓冲区的大小时,就会生成一个临时文件存放到指定的临时目录当中。
      factory.setSizeThreshold(1024 * 100); // 设置缓冲区的大小为100KB,如果不指定,那么缓冲区的大小默认是10KB
      // 设置上传时生成的临时文件的保存目录
      factory.setRepository(tmpFile);
      // 2、创建一个文件上传解析器
      ServletFileUpload upload = new ServletFileUpload(factory);
      // 监听文件上传进度
      upload.setProgressListener(
          new ProgressListener() {
            public void update(long pBytesRead, long pContentLength, int arg2) {
              System.out.println("文件大小为:" + pContentLength + ",当前已处理:" + pBytesRead);
              /**
               * 文件大小为:14608,当前已处理:4096 文件大小为:14608,当前已处理:7367 文件大小为:14608,当前已处理:11419
               * 文件大小为:14608,当前已处理:14608
               */
            }
          });
      // 解决上传文件名的中文乱码
      upload.setHeaderEncoding("gb2312");
      // 3、判断提交上来的数据是否是上传表单的数据
      if (!ServletFileUpload.isMultipartContent(request)) {
        // 按照传统方式获取数据
        return;
      }

      // 设置上传单个文件的大小的最大值,目前是设置为1024*1024字节,也就是1MB
      upload.setFileSizeMax(1024 * 1024);
      // 设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为10MB
      upload.setSizeMax(1024 * 1024 * 10);
      // 4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
      List<FileItem> list = upload.parseRequest(request);
      for (FileItem item : list) {
        // 如果fileitem中封装的是普通输入项的数据
        if (item.isFormField()) {
          String name = item.getFieldName();
          // 解决普通输入项的数据的中文乱码问题
          String value = item.getString("gb2312");
          // value = new String(value.getBytes("iso8859-1"),"UTF-8");
          System.out.println(name + "=" + value);
        } else { // 如果fileitem中封装的是上传文件
          // 得到上传的文件名称,
          filename = item.getName();
          System.out.println(filename);
          if (filename == null || filename.trim().equals("")) {
            continue;
          }
          // 注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如:  c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt
          // 处理获取到的上传文件的文件名的路径部分,只保留文件名部分
          filename = filename.substring(filename.lastIndexOf("\\") + 1);
          // 得到上传文件的扩展名
          String fileExtName = filename.substring(filename.lastIndexOf(".") + 1);
          // 如果需要限制上传的文件类型,那么可以通过文件的扩展名来判断上传的文件类型是否合法
          System.out.println("上传的文件的扩展名是:" + fileExtName);
          // 获取item中的上传文件的输入流
          InputStream in = item.getInputStream();
          // 得到文件保存的名称
          saveFilename = makeFileName(filename);
          // 得到文件的保存目录
          realSavePath = makePath(saveFilename, savePath);
          // 创建一个文件输出流
          FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename);
          // 创建一个缓冲区
          byte buffer[] = new byte[1024];
          // 判断输入流中的数据是否已经读完的标识
          int len = 0;
          // 循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
          while ((len = in.read(buffer)) > 0) {
            // 使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
            out.write(buffer, 0, len);
          }
          // 关闭输入流
          in.close();
          // 关闭输出流
          out.close();
          // 删除处理文件上传时生成的临时文件
          // item.delete();
          message = "文件上传成功!";

          Files files = new Files();
          files.setFilename(filename);
          files.setFileonlyname(saveFilename);
          files.setFilesroute(realSavePath);

          FileDao fileDao = new FileDao();
          fileDao.addOne(files, sid);
        }
      }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
      e.printStackTrace();
      request.setAttribute("message", "单个文件超出最大值!!!");
      request.getRequestDispatcher("user_view/file/file_message.jsp").forward(request, response);
      return;
    } catch (FileUploadBase.SizeLimitExceededException e) {
      e.printStackTrace();
      request.setAttribute("message", "上传文件的总的大小超出限制的最大值!!!");
      request.getRequestDispatcher("user_view/file/file_message.jsp").forward(request, response);
      return;
    } catch (Exception e) {
      message = "文件上传失败!";
      e.printStackTrace();
    }

    request.setAttribute("message", message);
    request.getRequestDispatcher("/user_view/file/file_message.jsp").forward(request, response);
  }
Exemple #25
0
  /**
   * 上传图片
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @RequestMapping(value = "/uploadImage")
  @ResponseBody
  public Map uploadImage(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    ConpanyUser users = (ConpanyUser) request.getSession().getAttribute(SessionString.USER_OBJ);

    Map<String, Object> map = new HashMap<String, Object>();
    if (users == null) {
      map.put("error", 1);
      map.put("message", "请登录后再上传");
      return map;
    }
    String savePath =
        FileManager.SAAS
            + users.getConpanyId()
            + File.separatorChar
            + FileManager.CUSTEMMER_INFOIMAGE
            + File.separatorChar;
    // String saveUrl  = request.getContextPath() + "/fileSrc/getOrgImg";
    HashMap<String, String> extMap = new HashMap<String, String>();
    extMap.put("image", "gif,jpg,jpeg,png,bmp");
    // 最大文件大小
    long maxSize = 2000000;
    response.setContentType("text/html; charset=UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
      map.put("error", 1);
      map.put("message", "请选择文件。");
      return map;
    }
    File uploadDir = new File(savePath);
    if (!uploadDir.isDirectory()) {
      uploadDir.mkdir();
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String ymd = sdf.format(new Date());
    File dirFile = new File(savePath);
    if (!dirFile.exists()) {
      dirFile.mkdirs();
    }
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    List items = null;
    try {
      items = upload.parseRequest(request);
    } catch (FileUploadException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    Iterator itr = items.iterator();
    while (itr.hasNext()) {
      FileItem item = (FileItem) itr.next();
      String fileName = item.getName();
      long fileSize = item.getSize();
      if (!item.isFormField()) {
        // 检查文件大小
        if (item.getSize() > maxSize) {
          // out.println(getError("上传文件大小超过限制。"));
          map.put("error", 1);
          map.put("message", "上传文件大小超过限制。最高位2m");
          return map;
        }
        // 检查扩展名
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)) {
          // out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
          map.put("success", 1);
          map.put("message", "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get("image") + "格式。");
          return map;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName =
            df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        FileUploadStatus fus = new FileUploadStatus();
        fus.setFileName(newFileName);
        fus.setFileNameCountSize(fileSize);
        fus.setPath(savePath);
        request.getSession().setAttribute("ImageFileUpLoad", fus);
        try {
          File uploadedFile = new File(savePath, newFileName);
          item.write(uploadedFile);

          ImageList ima = new ImageList();
          ima.setStartDate(new Date());
          ima.setLinkaddress(savePath + newFileName);
          ima.setFilesize(item.getSize());
          ima.setConpanyId(users.getConpanyId());
          ima.setFiletype(fileExt);
          ima.setUserId(users.getId());
          ima.setUserName(users.getTrueName());
          ima.setFileName(fileName);
          ima.setType("1");
          String md5 = DigestUtils.md5Hex(new FileInputStream(new File(ima.getLinkaddress())));
          ima.setMd5(md5);
          dao.add(ima);
          String path = request.getContextPath();
          String basePath =
              request.getScheme()
                  + "://"
                  + request.getServerName()
                  + ":"
                  + request.getServerPort()
                  + path
                  + "/weixin/public/getImage?id="
                  + ima.getId();
          ima.setWwwLinkAddress(basePath);
          dao.update(ima);
          map.put("error", 0);
          map.put("url", basePath);
          return map;
        } catch (Exception e) {
          map.put("error", 1);
          map.put("message", "上传文件失败。");
          return map;
        }
      }
    }
    return map;
  }