@Override
 public void parseRequestParameters(
     final Map<String, String> params, final Map<String, com.bradmcevoy.http.FileItem> files)
     throws RequestParseException {
   try {
     if (isMultiPart()) {
       parseQueryString(params, req.getQueryString());
       @SuppressWarnings("unchecked")
       final List<FileItem> items = new ServletFileUpload().parseRequest(req);
       for (final FileItem item : items) {
         if (item.isFormField()) params.put(item.getFieldName(), item.getString());
         else files.put(item.getFieldName(), new FileItemWrapper(item));
       }
     } else {
       final Enumeration<String> en = req.getParameterNames();
       while (en.hasMoreElements()) {
         final String nm = en.nextElement();
         final String val = req.getParameter(nm);
         params.put(nm, val);
       }
     }
   } catch (final FileUploadException ex) {
     throw new RequestParseException("FileUploadException", ex);
   } catch (final Throwable ex) {
     throw new RequestParseException(ex.getMessage(), ex);
   }
 }
 public void deployByZip(Map<String, Object> params) {
   ZipInputStream zipInputStream = null;
   try {
     FileItem file = (FileItem) params.get("processFile");
     if (null != file) {
       zipInputStream = new ZipInputStream(file.getInputStream());
       String deploymentId = StringUtil.getString(params.get("deploymentId"));
       DeploymentBuilder deploymentBuilder = modelService.createDeployment();
       deploymentBuilder.addZipInputStream(zipInputStream);
       // 有deploymentID则为更新,否则为新增
       if (StringUtil.isNotEmpty(deploymentId)) {
         deploymentBuilder.updateDeploymentId(deploymentId);
       }
       deploymentBuilder.deploy();
     }
   } catch (IOException e) {
     throw new FoxbpmWebException(e);
   } finally {
     if (null != zipInputStream) {
       try {
         zipInputStream.close();
       } catch (IOException e) {
         throw new FoxbpmWebException(e);
       }
     }
   }
 }
Exemple #3
0
  public void handle(FileItem item, Map<String, Object> result) {
    BlobWriter writer = blobManager.newFile(item.getContentType());
    OutputStream out = writer.getOutputStream();
    InputStream in = null;
    try {
      in = item.getInputStream();

      try {
        int size = 0;

        while ((size = in.read(buffer)) != -1) {
          out.write(buffer, 0, size);
        }
      } finally {
        IOTools.close(in, out);
      }

      BlobInfo info = writer.getBlobInfo();
      result.put("fileId", info.id());
      result.put("contentType", info.contentType());
      result.put("md5", info.md5());
      result.put("sucessful", "true");

      blobManager.commit(writer);
    } catch (Exception ex) {
      result.put("sucessful", "false");
      blobManager.cancel(writer);
    }
  }
Exemple #4
0
  /**
   * 注销健康卡提交页
   *
   * @param model
   * @param mfile
   * @author 韩友军<*****@*****.**>
   * @since 2012-11-20下午12:57:08
   */
  @SuppressWarnings("unchecked")
  @RequestMapping(value = "/doCancelCardByExcel.html", method = RequestMethod.POST)
  public String doCancelCardByExcelAction(ModelMap model, HttpServletRequest request) {

    DiskFileItemFactory objDiskFileItemFactory = new DiskFileItemFactory();
    objDiskFileItemFactory.setSizeThreshold(1024 * 1024); // 缓存
    ServletFileUpload objServletFileUpload = new ServletFileUpload(objDiskFileItemFactory);

    try {
      List<FileItem> fileItems = objServletFileUpload.parseRequest(request);
      Iterator<FileItem> iterator = fileItems.iterator();
      while (iterator.hasNext()) {
        FileItem fileItem = (FileItem) iterator.next();
        if (!fileItem.isFormField()) {
          String strPath = this.context.getRealPath("/upload/");
          File file = new File(strPath + new Date().getTime() + ".xls");
          fileItem.write(file);
          String strFilePath = file.getPath();
          Map<String, Object> mapData = cardBO.cancelCard(strFilePath);
          model.put("data", mapData);
          model.put("success", true);
        }
      }
    } catch (Exception e) {
      model.put("success", false);
    }
    return "card/do_cancel_card_by_excel.html";
  }
  private FileItem fetchFileFromRequest(HttpServletRequest request, String imageFieldName) {

    try {
      List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
      for (FileItem item : items) {
        if (!item.isFormField()) {
          String fieldname = item.getFieldName();

          if (fieldname.equals(imageFieldName)) {
            return item;
          }
        }
      }
    } catch (FileUploadException e) {
      e.printStackTrace();
    }

    try {
      throw new CkFileManagerPropertyException(
          String.format(
              "Field name %s was not found in the request. "
                  + "Are you sure this is the correct image field name?",
              imageFieldName));
    } catch (CkFileManagerPropertyException e) {
      e.printStackTrace();
    }

    return null;
  }
Exemple #6
0
 @Override
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
   if (!ServletFileUpload.isMultipartContent(request)) {
     response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
     return;
   }
   try {
     List<FileItem> files = uploadHandler.parseRequest(request);
     if (files.size() == 0) {
       response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
       return;
     }
     FileItem fileItem = files.get(0);
     if (!fileItem.getContentType().equals(Constants.CLASS_CONTENT_TYPE)
         || fileItem.isFormField()) {
       response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
       return;
     }
     String folderName =
         baseDir + request.getRequestURI().replaceAll("/", Constants.FILE_SEPARATOR);
     File folder = new File(folderName);
     if (folder.exists() && !folder.isDirectory()) {
       response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
       return;
     }
     if (!folder.exists()) {
       folder.mkdirs();
     }
     fileItem.write(new File(folderName + Constants.FILE_SEPARATOR + fileItem.getName()));
   } catch (Exception e) {
     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
     return;
   }
 }
  /**
   * Handles the HTTP <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // processRequest(request, response);
    String p = "";
    ProfileParser pp = new ProfileParser();

    try {

      List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

      for (FileItem item : items) {
        if (item.isFormField()) {
          // String ajaxUpdateResult = "Field " + item.getFieldName() +
          // " with value: " + item.getString() + " is successfully read\n\r";
        } else {
          // String fileName = item.getName();
          InputStream content = item.getInputStream();
          // response.setContentType("text/plain");
          // response.setCharacterEncoding("UTF-8");
          p = pp.parseProfile(content);
          // System.out.println(Streams.asString(content));
        }
      }
    } catch (FileUploadException e) {
      throw new ServletException("Parsing file upload failed.", e);
    }

    // InputStream fileInput = request.getInputStream();
    // String p = pp.parseProfile(fileInput);
    response.getWriter().write(p);
  }
  private static FileItem prepareFileItemFromInputStream(
      PipelineContext pipelineContext, InputStream inputStream, int scope) {
    // Get FileItem
    final FileItem fileItem = prepareFileItem(pipelineContext, scope);
    // Write to file
    OutputStream os = null;
    try {
      os = fileItem.getOutputStream();
      copyStream(inputStream, os);
    } catch (IOException e) {
      throw new OXFException(e);
    } finally {
      if (os != null) {
        try {
          os.close();
        } catch (IOException e) {
          throw new OXFException(e);
        }
      }
    }
    // Create file if it doesn't exist (necessary when the file size is 0)
    final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
    try {
      storeLocation.createNewFile();
    } catch (IOException e) {
      throw new OXFException(e);
    }

    return fileItem;
  }
  private static String uploadPhoto(HttpServletRequest request) {
    logger.debug("load photo");
    try {
      File fileSaveDir = new File(SAVE_DIR);
      if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
      }

      FileItem fileItem = (FileItem) request.getAttribute("photo");
      if (fileItem == null) {
        return null;
      }
      String uuidFileName = UUID.randomUUID().toString() + "." + PHOTO_TYPE;
      File uploadedFile = new File(SAVE_DIR + File.separator + uuidFileName);
      uploadedFile.createNewFile();
      OutputStream imageOutput = new FileOutputStream(uploadedFile);
      if (!resizeImage(fileItem.getInputStream(), imageOutput, PHOTO_WIDTH, PHOTO_HEIGHT)) {
        throw new Exception("Failed to resize the image");
      }
      imageOutput.flush();
      imageOutput.close();
      //			fileItem.write(uploadedFile);
      return uuidFileName;
    } catch (Exception e) {
      logger.error("Error on saving uploaded photo.", e);
      return null;
    }
  }
Exemple #10
0
  public String createLocalImage(List<FileItem> fileItems) {
    String result = "";
    FileItem imgData = null;
    String userId = "";
    for (int i = 0; i < fileItems.size(); i++) {
      FileItem item = fileItems.get(i);
      if (!item.isFormField()) {
        // 图片数据
        imgData = item;
      }

      if (item.isFormField()) {
        if (item.getFieldName().equals("userId")) {
          userId = item.getString();
        }
      }
    }
    String imgPath = comicService.createLocalImage(userId, imgData);

    // 处理全路径,返回相对路径即可
    if (imgPath.contains("uploadFile")) {
      // 先从字符串中找到文件夹uploadFile的位置,再加上uploadFile的长度10,即可截取到下属文件路径
      int position = imgPath.lastIndexOf("uploadFile");
      result = imgPath.substring(position + 11);
    } else {
      result = imgPath;
    }

    return result;
  }
  /**
   * @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();
    }
  }
  public void upload(
      @Observes ControllerFound event,
      MutableRequest request,
      MultipartConfig config,
      Validator validator) {

    if (!ServletFileUpload.isMultipartContent(request)) {
      return;
    }

    logger.info("Request contains multipart data. Try to parse with commons-upload.");

    final Multiset<String> indexes = HashMultiset.create();
    final Multimap<String, String> params = LinkedListMultimap.create();

    ServletFileUpload uploader = createServletFileUpload(config);

    UploadSizeLimit uploadSizeLimit =
        event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class);
    uploader.setSizeMax(
        uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit());
    uploader.setFileSizeMax(
        uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit());
    logger.debug(
        "Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax());

    try {
      final List<FileItem> items = uploader.parseRequest(request);
      logger.debug(
          "Found {} attributes in the multipart form submission. Parsing them.", items.size());

      for (FileItem item : items) {
        String name = item.getFieldName();
        name = fixIndexedParameters(name, indexes);

        if (item.isFormField()) {
          logger.debug("{} is a field", name);
          params.put(name, getValue(item, request));

        } else if (isNotEmpty(item)) {
          logger.debug("{} is a file", name);
          processFile(item, name, request);

        } else {
          logger.debug("A file field is empty: {}", item.getFieldName());
        }
      }

      for (String paramName : params.keySet()) {
        Collection<String> paramValues = params.get(paramName);
        request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()]));
      }

    } catch (final SizeLimitExceededException e) {
      reportSizeLimitExceeded(e, validator);

    } catch (FileUploadException e) {
      reportFileUploadException(e, validator);
    }
  }
  @Override
  public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
      throws UploadActionException {
    if (logger.isDebugEnabled()) {
      logger.debug(
          "The id = "
              + request.getParameter("pid")
              + " imageNum = "
              + request.getParameter("imageNum"));
    }
    ContentholderDAO cDAO = contentholderDAOProvider.get();
    ContentitemsDAO itemDAO = itemDAOProvider.get();
    String idStr = request.getParameter("pid");
    String imageNum = request.getParameter("imageNum");
    Integer id = Integer.parseInt(idStr);
    Contentholder holder = cDAO.get(id);
    GharondaThumbnails stn = new GharondaThumbnails(getServletContext().getRealPath("/"));
    BaseContentSvcHelper helper = null;
    try {
      helper = new BaseContentSvcHelper(imageNum, holder, stn, cDAO, itemDAO);
    } catch (Exception e) {
      e.printStackTrace();
    }
    for (FileItem item : sessionFiles) {
      try {
        helper.store(item.getInputStream());
        break;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    removeSessionFileItems(request, true);
    return "";
  }
  @Issue("JENKINS-30941")
  @Test
  public void cleanUpSucceeds() throws Exception {
    /** Issue was just present on Linux not windows - but the test will run on both */
    final String credentialsId = "zipfile";

    /* do the dance to get a simple zip file into jenkins */
    InputStream zipStream = this.getClass().getResourceAsStream("a.zip");
    try {
      assertThat(zipStream, is(not(nullValue())));
      File zip = tmp.newFile("a.zip");
      FileUtils.copyInputStreamToFile(zipStream, zip);
      FileItem fi = new FileItemImpl(zip);
      FileCredentialsImpl fc =
          new FileCredentialsImpl(
              CredentialsScope.GLOBAL, credentialsId, "Just a zip file", fi, fi.getName(), null);
      CredentialsProvider.lookupStores(j.jenkins)
          .iterator()
          .next()
          .addCredentials(Domain.global(), fc);
    } finally {
      IOUtils.closeQuietly(zipStream);
      zipStream = null;
    }

    final String unixFile = "/dir/testfile.txt";
    final String winFile =
        unixFile.replace(
            "/", "\\\\"); /* two \\ as we escape the code and then escape for the script */
    // if this file does not have a line ending then the text is not echoed to the log.
    // fixed in workflow 1.11+ (which is not released at the time of writing)
    final String contents = "Test of ZipFileBinding\n";

    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(
        new CpsFlowDefinition(
            ""
                + "node {\n"
                + "  withCredentials([[$class: 'ZipFileBinding', credentialsId: '"
                + credentialsId
                + "', variable: 'ziploc']]) {\n"
                + (Functions.isWindows()
                    ? "    bat 'type %ziploc%" + winFile + "'\n"
                    : "    sh 'cat ${ziploc}" + unixFile + "'\n")
                + "    def text = readFile encoding: 'UTF-8', file: \"${env.ziploc}"
                + unixFile
                + "\"\n"
                + "    if (!text.equals('''"
                + contents
                + "''')) {\n"
                + "      error ('incorrect details from zip file')\n"
                + "    }\n"
                + "  }\n"
                + "}\n",
            true));

    WorkflowRun run = p.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(run);
    j.assertLogContains(contents, run);
  }
  /**
   * Delete an uploaded file.
   *
   * @param request
   * @param response
   * @return FileItem
   * @throws IOException
   */
  protected static FileItem removeUploadedFile(
      HttpServletRequest request, HttpServletResponse response) throws IOException {

    String parameter = request.getParameter(PARAM_REMOVE);
    FileItem item = findFileItem(getSessionFileItems(request), parameter);
    if (item != null) {
      getSessionFileItems(request).remove(item);
      renderXmlResponse(request, response, DELETED_TRUE);
      logger.debug(
          "UPLOAD-SERVLET ("
              + request.getSession().getId()
              + ") removeUploadedFile: "
              + parameter
              + " "
              + item.getName()
              + " "
              + item.getSize());
    } else {
      renderXmlResponse(request, response, ERROR_ITEM_NOT_FOUND);
      logger.info(
          "UPLOAD-SERVLET ("
              + request.getSession().getId()
              + ") removeUploadedFile: "
              + parameter
              + " unable to delete file because it isn't in session.");
    }

    return item;
  }
  /**
   * Realizando o upload do arquivo informado
   *
   * @author Raphael Rossiter
   * @date 30/07/2009
   * @param HttpServletRequest
   */
  private Object[] recebendoObjetos(HttpServletRequest httpServletRequest)
      throws FileUploadException {

    Object[] parametrosFormulario = new Object[2];

    DiskFileUpload upload = new DiskFileUpload();

    List itens = upload.parseRequest(httpServletRequest);
    FileItem fileItem = null;

    if (itens != null) {

      Iterator iter = itens.iterator();

      while (iter.hasNext()) {

        fileItem = (FileItem) iter.next();

        if (fileItem.getFieldName().equals("arquivoAnexo")) {

          parametrosFormulario[0] = fileItem;
        }

        if (fileItem.getFieldName().equals("observacaoAnexo")) {

          parametrosFormulario[1] = fileItem.getString();
        }
      }
    }

    return parametrosFormulario;
  }
Exemple #17
0
 @Override
 protected void service() throws ServletException, IOException {
   HttpServletRequest request = getRequest();
   String path = null;
   DiskFileItemFactory factory =
       new DiskFileItemFactory(5 * 1024, new File(Configuration.getContextPath("temp")));
   ServletFileUpload upload = new ServletFileUpload(factory);
   upload.setSizeMax(3 * 1024 * 1024);
   try {
     List<FileItem> items = upload.parseRequest(request);
     FileItem fileItem = null;
     if (items != null
         && items.size() > 0
         && StringUtils.isNotBlank((fileItem = items.get(0)).getName())) {
       String fileName = fileItem.getName();
       if (!fileName.endsWith(".jpg")
           && !fileName.endsWith(".gif")
           && !fileName.endsWith(".png")) {
         writeText("format_error");
         return;
       }
       path = ImageUtil.generatePath(fileItem.getName());
       IOUtil.copy(fileItem.getInputStream(), Configuration.getContextPath(path));
       fileItem.delete();
       writeText(Configuration.getSiteUrl(path));
     }
   } catch (FileUploadException e) {
     throw new RuntimeException(e);
   }
 }
Exemple #18
0
  public static final File writeFileItemToFolder(
      FileItem fileItem, File folder, boolean overwrite, boolean rename) throws IOException {
    if (!folder.isDirectory()) {
      return null;
    }
    File file =
        new File(
            URLHelper.mergePath(
                folder.getAbsolutePath(),
                StringHelper.createFileName(StringHelper.getFileNameFromPath(fileItem.getName()))));

    if (!file.exists()) {
      file.createNewFile();
    } else {
      if (!overwrite && !rename) {
        throw new FileExistsException("File already exists.");
      }
      if (rename) {
        file = ResourceHelper.getFreeFileName(file);
      }
    }
    InputStream in = null;
    try {
      in = fileItem.getInputStream();
      writeStreamToFile(in, file);
      return file;
    } catch (IOException e) {
      ResourceHelper.closeResource(in);
      file.delete();
      throw e;
    } finally {
      ResourceHelper.closeResource(in);
    }
  }
  @SuppressWarnings("unchecked")
  private void parseParams(HttpServletRequest req) {
    try {
      Map m = req.getParameterMap();
      for (Object e0 : m.entrySet()) {
        Map.Entry<String, ?> e = (Map.Entry<String, ?>) e0;
        Object v = e.getValue();
        String vs =
            v instanceof String[]
                ? StringUtils.join((String[]) v, "")
                : ObjectUtils.toString(v, "");
        setString(e.getKey(), vs);
      }

      if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = createFileUpload();
        List<FileItem> fileItems = upload.parseRequest(req);
        for (FileItem fileItem : fileItems) {
          if (fileItem.isFormField()) {
            setString(fileItem.getFieldName(), fileItem.getString(Charsets.DEFAULT));
          } else {
            put(fileItem.getFieldName(), fileItem);
          }
        }
      }
    } catch (Exception e) {
      throw new WebException(e);
    }
  }
Exemple #20
0
  public Photo saveImg(FileItem item) throws Exception {
    Photo photo = new Photo();
    String filename = item.getName();
    if (filename == null || filename.length() == 0) {
      log.error("img name illegal");
      return null;
    }
    int index = filename.lastIndexOf(".");
    String type = filename.substring(index + 1);
    if (!ImgTools.checkImgFormatValidata(type)) {
      log.error("img type illegal");
      return null;
    }
    ObjectId id = ObjectIdGenerator.generate();
    // filename = new ObjectId() + filename.substring(index);
    photo.setId(id.toString());
    photo.setType(type);

    GridFS mphoto = new GridFS(MongoDBPool.getInstance().getDB(), collection);
    GridFSInputFile in = null;
    in = mphoto.createFile(item.getInputStream());
    in.setId(id);
    in.setFilename(id.toString());
    in.setContentType(type);
    in.save();
    item.getInputStream().close();
    return photo;
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Fachada fachada = Fachada.obterInstancia();
    String acao = "";
    List<FileItem> items = null;
    if (ServletFileUpload.isMultipartContent(request)) {

      try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
      } catch (FileUploadException e1) {

        e1.printStackTrace();
      }

      for (FileItem item : items) {
        if (item.getFieldName().equals("acao")) {
          acao = item.getString();
        }
      }
    } else {
      acao = request.getParameter("acao");
    }

    try {
      if (acao.equals("deletar")) {
        deletarMembro(request, fachada);
      } else {
        cadastrarEditarMembro(request, response, fachada, acao, items);
      }
      request.getRequestDispatcher("sucesso.jsp").forward(request, response);
    } catch (Exception e) {
      e.printStackTrace();
      request.getRequestDispatcher("falha.jsp").forward(request, response);
    }
  }
 @RequestMapping(value = "/UploadFile.htm")
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   boolean isMultipart = ServletFileUpload.isMultipartContent(request);
   FileItemFactory factory = new DiskFileItemFactory();
   ServletFileUpload upload = new ServletFileUpload(factory);
   File file = null;
   try {
     List<FileItem> items = upload.parseRequest(request);
     if (isMultipart) {
       for (FileItem item : items) {
         if (!item.isFormField()) {
           String name = new File(item.getName()).getName();
           file = new File(request.getRealPath(File.separator) + File.separator + name);
           item.write(file);
         }
       }
       readFileImpl.readCSVFile(file);
       request.getRequestDispatcher("jsp/display.jsp").forward(request, response);
     }
   } catch (FileUploadException e) {
     e.printStackTrace();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    // 设置上传文件大小的上限,-1表示无上限
    fileUpload.setSizeMax(-1);
    // 上传文件,解析表单中包含的文件字段和普通字段
    try {
      List<FileItem> items = fileUpload.parseRequest(request);
      if (items.size() > 0) {
        FileItem item = (FileItem) items.get(0);
        String name = item.getName();
        String path = getServletContext().getRealPath(Constants.UPLOAD_IMG_PATH) + "/" + name;
        logger.info("上传用户图片信息,图片名:" + name + ";上传路径:" + path);
        // 实现图片上传
        try {
          item.write(new File(path));
          // 就用户头像路径保存.
          User user = new User();
          user.setPhone(request.getHeader("owner"));
          user.setImgPath(Constants.UPLOAD_IMG_PATH + "/" + name);
          userService.saveOrUpdateUserInfo(user);

        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

    } catch (FileUploadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 public Map upload(HttpServletRequest request, FileItem item) {
   Map mapList = new HashMap();
   try {
     if (item.isFormField()) {
       // 普通表单
     } else {
       String fieldName = item.getFieldName();
       String fileName = item.getName();
       // 如果文件域没有填写内容,或者填写的文件不存在
       if ("".equals(fileName) || item.getSize() == 0) {
         return mapList;
       }
       String userfilepath = request.getRealPath("upload");
       String date = "/" + fnu.getDate8() + "/";
       String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
       String newfilename = fnu.getUUID() + "." + extName;
       File uploadedFile = new File(userfilepath + date + newfilename);
       if (!uploadedFile.exists()) { // 如果要写入的文件或目录不存在,那么试着创建要写入的目录,以便写入文件
         uploadedFile.getParentFile().mkdirs();
       }
       item.write(uploadedFile);
       mapList.put("fieldname", fieldName);
       mapList.put(
           "filename",
           fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.length()));
       mapList.put("extname", extName);
       mapList.put("filepath", userfilepath + date + newfilename);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return mapList;
 }
  /*
   * (non-Javadoc)
   *
   * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFile(java.lang.String)
   */
  public File[] getFile(String fieldName) {
    List<FileItem> items = files.get(fieldName);

    if (items == null) {
      return null;
    }

    List<File> fileList = new ArrayList<File>(items.size());
    for (FileItem fileItem : items) {
      File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
      if (fileItem.isInMemory() && storeLocation != null && !storeLocation.exists()) {
        try {
          storeLocation.createNewFile();
        } catch (IOException e) {
          if (LOG.isErrorEnabled()) {
            LOG.error(
                "Cannot write uploaded empty file to disk: " + storeLocation.getAbsolutePath(), e);
          }
        }
      }
      fileList.add(storeLocation);
    }

    return fileList.toArray(new File[fileList.size()]);
  }
  protected File forceToFile(FileItem fileItem) throws IOException, ServletException {
    if (fileItem.isInMemory()) {
      String name = fileItem.getName();

      if (null == name) {
        throw new IllegalArgumentException("FileItem has null name");
      }

      // some browsers (IE, Chrome) pass an absolute filename, we just want the name of the file, no
      // paths
      name = name.replace('\\', '/');
      if (name.length() > 2 && name.charAt(1) == ':') {
        name = name.substring(2);
      }
      name = new File(name).getName();

      File tmpFile = File.createTempFile(name, null);
      try {
        fileItem.write(tmpFile);
        return tmpFile;
      } catch (Exception e) {
        throw new ServletException("Failed to persist uploaded file to disk", e);
      }
    } else {
      return ((DiskFileItem) fileItem).getStoreLocation();
    }
  }
 private FileItem getParameter(List<FileItem> items, String parameterName) {
   for (FileItem item : items) {
     if (parameterName.equals(item.getFieldName())) {
       return item;
     }
   }
   return null;
 }
  @Override
  public void execute(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession session = request.getSession();
    ResourceBundle bundle = (ResourceBundle) session.getAttribute("bundle");

    String jsonError = "";
    ServletContext context = request.getSession().getServletContext();
    response.setContentType("application/json");

    try {
      if (ServletFileUpload.isMultipartContent(request)) {
        String fileName;
        String filePath;
        FileType.Type type;
        List<FileItem> multiparts =
            new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : multiparts) {
          if (!item.isFormField()) {
            fileName = new File(item.getName()).getName();
            type = FileType.getType(fileName);
            if (type != null) {
              filePath = context.getRealPath(type.getPath());
              SecureRandom random = new SecureRandom();
              fileName =
                  new BigInteger(130, random).toString(32) + FileType.parseFileFormat(fileName);
              item.write(new File(filePath + File.separator + fileName));
              request
                  .getSession()
                  .setAttribute(
                      "urlCat",
                      ServerLocationUtils.getServerPath(request) + type.getPath() + "/" + fileName);
              LOG.debug("File uploaded successfully");
              response
                  .getWriter()
                  .print(
                      new JSONObject()
                          .put(
                              "success",
                              UTF8.encoding(bundle.getString("notification.upload.file.success"))));
            } else {
              jsonError = UTF8.encoding(bundle.getString("notification.wrong.file.format"));
            }
          }
        }
      } else {
        jsonError = UTF8.encoding(bundle.getString("notification.request.error"));
      }
    } catch (Exception e) {
      LOG.error(e.getLocalizedMessage(), e);
      jsonError = UTF8.encoding(bundle.getString("notification.upload.file.error"));
    } finally {
      if (!jsonError.isEmpty()) {
        response.getWriter().print(new JSONObject().put("error", jsonError));
      }
    }
  }
 private void processFile(FileItem item) {
   imageSize = item.getSize();
   try {
     imageIs = item.getInputStream();
   } catch (IOException e) {
     imageIs = null;
     imageSize = 0;
   }
 }
 /**
  * Process the multipart form
  *
  * @param nav The Navigation object
  */
 public void process() {
   for (FileItem item : files) {
     if (item.isFormField()) {
       map.put(item.getFieldName(), item.getString());
     } else {
       processFile(item);
     }
   }
 }