@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);
    }
  }
Example #2
0
 @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 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 executeAction to save the received files in a custom place and delete this items from
   * session.
   */
  @Override
  public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
      throws UploadActionException {
    String response = "";
    HttpSession session = request.getSession(true);
    if (sessionFiles.size() == 0) {
      LOG.info("No hay imagenes en la session");
      return "No hay imagenes en la session";
    }
    if (session.getAttribute(ATTR_ARCHIVOS) == null)
      session.setAttribute(ATTR_ARCHIVOS, new ArrayList<String>());

    List<String> photos = (List<String>) session.getAttribute(ATTR_ARCHIVOS);

    for (FileItem item : sessionFiles) {
      if (false == item.isFormField()) {
        try {
          // / Create a new file based on the remote file name in the
          // client
          // String saveName =
          // item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+",
          // "_");
          // File file =new File("/tmp/" + saveName);

          // / Create a temporary file placed in /tmp (only works in
          // unix)
          // File file = File.createTempFile("upload-", ".bin", new
          // File("/tmp"));

          // / Create a temporary file placed in the default system
          // temp folder

          String name = item.getName();
          int posPunto = name.lastIndexOf(".");
          String ext = name.substring(posPunto + 1);

          File file = File.createTempFile("gha", "." + ext);

          item.write(file);

          // / Save a list with the received files
          receivedFiles.put(item.getFieldName(), file);
          receivedContentTypes.put(item.getFieldName(), item.getContentType());
          photos.add(file.getName());

          // / Send a customized message to the client.
          response += file.getName();

        } catch (Exception e) {
          throw new UploadActionException(e);
        }
      }
    }

    // / Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    // / Send your customized message to the client.
    return response;
  }
Example #5
0
 /**
  * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the
  * given {@link HttpServletRequest}
  *
  * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a
  *     multipart POST request
  * @param httpServletRequest The {@link HttpServletRequest} that contains the mutlipart POST data
  *     to be sent via the {@link PostMethod}
  */
 @SuppressWarnings("unchecked")
 private void handleMultipartPost(
     PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
     throws ServletException {
   // Create a factory for disk-based file items
   DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
   // Set factory constraints
   diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
   diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
   // Create a new file upload handler
   ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
   // Parse the request
   try {
     // Get the multipart items as a list
     List<FileItem> listFileItems =
         (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
     // Create a list to hold all of the parts
     List<Part> listParts = new ArrayList<Part>();
     // Iterate the multipart items list
     for (FileItem fileItemCurrent : listFileItems) {
       // If the current item is a form field, then create a string part
       if (fileItemCurrent.isFormField()) {
         StringPart stringPart =
             new StringPart(
                 fileItemCurrent.getFieldName(), // The field name
                 fileItemCurrent.getString() // The field value
                 );
         // Add the part to the list
         listParts.add(stringPart);
       } else {
         // The item is a file upload, so we create a FilePart
         FilePart filePart =
             new FilePart(
                 fileItemCurrent.getFieldName(), // The field name
                 new ByteArrayPartSource(
                     fileItemCurrent.getName(), // The uploaded file name
                     fileItemCurrent.get() // The uploaded file contents
                     ));
         // Add the part to the list
         listParts.add(filePart);
       }
     }
     MultipartRequestEntity multipartRequestEntity =
         new MultipartRequestEntity(
             listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
     postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
     // The current content-type header (received from the client) IS of
     // type "multipart/form-data", but the content-type header also
     // contains the chunk boundary string of the chunks. Currently, this
     // header is using the boundary of the client request, since we
     // blindly copied all headers from the client request to the proxy
     // request. However, we are creating a new request with a new chunk
     // boundary string, so it is necessary that we re-set the
     // content-type string to reflect the new chunk boundary string
     postMethodProxyRequest.setRequestHeader(
         STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType());
   } catch (FileUploadException fileUploadException) {
     throw new ServletException(fileUploadException);
   }
 }
  public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception {
    PrivateKey privateKey = null;
    Certificate[] certs = null;
    while (uploadedFilesIterator.hasNext()) {
      FileItem fileItem = uploadedFilesIterator.next();
      if (!fileItem.isFormField()) {
        if ("keyFile".equals(fileItem.getFieldName())) {
          KeyFactory kf = KeyFactory.getInstance("RSA");
          privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get()));
        }
        if ("certFile".equals(fileItem.getFieldName())) {
          CertificateFactory cf = CertificateFactory.getInstance("X.509");
          certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {});
        }
      }
    }

    if (privateKey == null || certs == null) {
      throw new WebApplicationException(
          Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build());
    }

    keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs);
    save();
  }
  /**
   * 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;
  }
  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;
  }
  /**
   * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, containing
   * Spring MultipartFile instances and a Map of multipart parameter.
   *
   * @param fileItems the Commons FileIterms to parse
   * @param encoding the encoding to use for form fields
   * @return the Spring MultipartParsingResult
   * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
   */
  protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles =
        new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
      if (fileItem.isFormField()) {
        String value;
        String partEncoding = determineEncoding(fileItem.getContentType(), encoding);
        if (partEncoding != null) {
          try {
            value = fileItem.getString(partEncoding);
          } catch (UnsupportedEncodingException ex) {
            if (logger.isWarnEnabled()) {
              logger.warn(
                  "Could not decode multipart item '"
                      + fileItem.getFieldName()
                      + "' with encoding '"
                      + partEncoding
                      + "': using platform default");
            }
            value = fileItem.getString();
          }
        } else {
          value = fileItem.getString();
        }
        String[] curParam = multipartParameters.get(fileItem.getFieldName());
        if (curParam == null) {
          // simple form field
          multipartParameters.put(fileItem.getFieldName(), new String[] {value});
        } else {
          // array of simple form fields
          String[] newParam = StringUtils.addStringToArray(curParam, value);
          multipartParameters.put(fileItem.getFieldName(), newParam);
        }
        multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType());
      } else {
        // multipart file field
        CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
        multipartFiles.add(file.getName(), file);
        if (logger.isDebugEnabled()) {
          logger.debug(
              "Found multipart file ["
                  + file.getName()
                  + "] of size "
                  + file.getSize()
                  + " bytes with original filename ["
                  + file.getOriginalFilename()
                  + "], stored "
                  + file.getStorageDescription());
        }
      }
    }
    return new MultipartParsingResult(
        multipartFiles, multipartParameters, multipartParameterContentTypes);
  }
  /**
   * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse response)
      throws ServletException, IOException {
    // Extract the relevant content from the POST'd form
    if (ServletFileUpload.isMultipartContent(req)) {
      Map<String, String> responseMap;
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);

      // Parse the request
      String deploymentType = null;
      String version = null;
      String fileName = null;
      InputStream artifactContent = null;
      try {
        List<FileItem> items = upload.parseRequest(req);
        for (FileItem item : items) {
          if (item.isFormField()) {
            if (item.getFieldName().equals("deploymentType")) { // $NON-NLS-1$
              deploymentType = item.getString();
            } else if (item.getFieldName().equals("version")) { // $NON-NLS-1$
              version = item.getString();
            }
          } else {
            fileName = item.getName();
            if (fileName != null) fileName = FilenameUtils.getName(fileName);
            artifactContent = item.getInputStream();
          }
        }

        // Default version is 1.0
        if (version == null || version.trim().length() == 0) {
          version = "1.0"; // $NON-NLS-1$
        }

        // Now that the content has been extracted, process it (upload the artifact to the s-ramp
        // repo).
        responseMap = uploadArtifact(deploymentType, fileName, version, artifactContent);
      } catch (SrampAtomException e) {
        responseMap = new HashMap<String, String>();
        responseMap.put("exception", "true"); // $NON-NLS-1$ //$NON-NLS-2$
        responseMap.put("exception-message", e.getMessage()); // $NON-NLS-1$
        responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); // $NON-NLS-1$
      } catch (Throwable e) {
        responseMap = new HashMap<String, String>();
        responseMap.put("exception", "true"); // $NON-NLS-1$ //$NON-NLS-2$
        responseMap.put("exception-message", e.getMessage()); // $NON-NLS-1$
        responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); // $NON-NLS-1$
      } finally {
        IOUtils.closeQuietly(artifactContent);
      }
      writeToResponse(responseMap, response);
    } else {
      response.sendError(
          HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
          Messages.i18n.format("DeploymentUploadServlet.ContentTypeInvalid")); // $NON-NLS-1$
    }
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
      chain.doFilter(request, response);
      return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    boolean isMultipartContent = FileUpload.isMultipartContent(httpRequest);
    if (!isMultipartContent) {
      chain.doFilter(request, response);
      return;
    }

    DiskFileUpload upload = new DiskFileUpload();
    if (repositoryPath != null) upload.setRepositoryPath(repositoryPath);

    try {
      List list = upload.parseRequest(httpRequest);
      final Map map = new HashMap();
      for (int i = 0; i < list.size(); i++) {
        FileItem item = (FileItem) list.get(i);
        String str = item.getString();
        if (item.isFormField()) map.put(item.getFieldName(), new String[] {str});
        else httpRequest.setAttribute(item.getFieldName(), item);
      }

      chain.doFilter(
          new HttpServletRequestWrapper(httpRequest) {
            public Map getParameterMap() {
              return map;
            }

            public String[] getParameterValues(String name) {
              Map map = getParameterMap();
              return (String[]) map.get(name);
            }

            public String getParameter(String name) {
              String[] params = getParameterValues(name);
              if (params == null) return null;
              return params[0];
            }

            public Enumeration getParameterNames() {
              Map map = getParameterMap();
              return Collections.enumeration(map.keySet());
            }
          },
          response);
    } catch (FileUploadException ex) {
      ServletException servletEx = new ServletException();
      servletEx.initCause(ex);
      throw servletEx;
    }
  }
Example #12
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (ServletFileUpload.isMultipartContent(request)) {
      UploadTools uploadTools = new UploadTools();
      String path = request.getSession().getServletContext().getRealPath("/") + "/";
      ServletFileUpload upload = uploadTools.initUpload(path);
      String image = null, introduce = null, strategy = null;
      try {
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
          FileItem item = iter.next();

          if ("introduce".equals(item.getFieldName())) {
            introduce = item.getString(request.getCharacterEncoding());
          } else if ("strategy".equals(item.getFieldName())) {
            strategy = item.getString(request.getCharacterEncoding());
          } else {
            image = uploadTools.uploadFile(path, item);
            System.out.println(image);
          }
        }
      } catch (FileUploadException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }

      HttpSession session = request.getSession(true);
      Object cityName = session.getAttribute("searchcity");
      // System.out.println(cityName);
      // Object image1 = session.getAttribute("image");

      DBTools dbtools = new DBTools();
      String sql =
          "update city set c_introduce='"
              + introduce
              + "',c_path='"
              + image
              + "',c_strategy='"
              + strategy
              + "' where c_name='"
              + cityName
              + "';";

      int count = dbtools.update(sql);
      if (count > 0) {
        response.sendRedirect("success.jsp");
      }
    }
  }
Example #13
0
  public String createAnimation(List<FileItem> fileItems) {
    FileItem shotData = null;
    String userId = "";
    String name = "";
    String content = "";
    String app = "";

    for (int i = 0; i < fileItems.size(); i++) {
      FileItem item = fileItems.get(i);
      if (!item.isFormField()) {
        // 图片数据
        shotData = item;
      }

      if (item.isFormField()) {

        if (item.getFieldName().equals("userId")) {
          userId = item.getString();
        }

        if (item.getFieldName().equals("name")) {
          try {
            name = item.getString("UTF-8");
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          }
        }

        if (item.getFieldName().equals("content")) {
          try {
            content = item.getString("UTF-8");
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          }
        }

        if (item.getFieldName().equals("app")) {
          try {
            app = item.getString("UTF-8");
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          }
        }
      }
    } // 取参数完成

    String result = comicService.createAnimation(shotData, userId, name, content, app);

    return result;
  }
  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;
  }
Example #15
0
  private void parseRequest(
      HttpServletRequest request, Map<String, String> parameters, List<file> files)
      throws IOException {
    if (ServletFileUpload.isMultipartContent(request)) {
      List<FileItem> fileItems = parseMultipartRequest(request);

      long fileSizeMaxMB = ServerConfig.webServerUploadMax();
      long fileSizeMax = fileSizeMaxMB > 0 ? fileSizeMaxMB * NumericUtils.Megabyte : Long.MAX_VALUE;

      for (FileItem fileItem : fileItems) {
        if (!fileItem.isFormField()) {
          if (fileItem.getSize() > fileSizeMax)
            throw new RuntimeException(
                Resources.format(
                    "Exception.fileSizeLimitExceeded", fileItem.getName(), fileSizeMaxMB));
          files.add(new file(fileItem));
        } else
          parameters.put(fileItem.getFieldName(), fileItem.getString(encoding.Default.toString()));
      }
    } else {
      @SuppressWarnings("unchecked")
      Map<String, String[]> requestParameters = request.getParameterMap();

      for (String name : requestParameters.keySet()) {
        String[] values = requestParameters.get(name);
        parameters.put(name, values.length != 0 ? values[0] : null);
      }
    }

    parameters.put(Json.ip.get(), request.getRemoteAddr());
  }
  /**
   * @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();
    }
  }
Example #17
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;
  }
	public File doAttachment(HttpServletRequest request)
			throws ServletException, IOException {
		File file = null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<?> items = upload.parseRequest(request);
			Iterator<?> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					parameters
							.put(item.getFieldName(), item.getString("UTF-8"));
				} else {
					File tempFile = new File(item.getName());
					file = new File(sc.getRealPath("/") + savePath, tempFile
							.getName());
					item.write(file);
				}
			}
		} catch (Exception e) {
			Logger logger = Logger.getLogger(SendAttachmentMailServlet.class);
			logger.error("邮件发送出了异常", e);
		}
		return file;
	}
  /** @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);
    }
  }
Example #20
0
 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;
 }
Example #21
0
 private FileTemp getFileInfo(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   try {
     FileItemFactory factory = new DiskFileItemFactory();
     ServletFileUpload upload = new ServletFileUpload(factory);
     List<FileItem> items = upload.parseRequest(request);
     String status = "";
     InputStream is = null;
     String fileName = "";
     for (Iterator<FileItem> i = items.iterator(); i.hasNext(); ) {
       FileItem item = i.next();
       if (item.isFormField()) {
         if (item.getFieldName().equals("status_text")) {
           status = new String(item.get());
         }
       } else {
         fileName = item.getName();
         is = item.getInputStream();
       }
     }
     return new FileTemp(fileName, is, status);
   } catch (FileUploadException e) {
     return null;
   }
 }
Example #22
0
  @SuppressWarnings("null")
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    //
    if (!isMultipart) {
      return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    // factory.setRepository(new File("d:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    // System.out.println(empid);
    try {
      // out = response.getWriter( );
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      while (i.hasNext()) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
          // Get the uploaded file parameters
          String fieldName = fi.getFieldName();
          String fileName = fi.getName();
          String contentType = fi.getContentType();
          boolean isInMemory = fi.isInMemory();
          long sizeInBytes = fi.getSize();
          // Write the file
          if (fileName.lastIndexOf("\\") >= 0) {
            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
          } else {
            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
          }
          fi.write(file);
          readBOM(file);
          break;
        }
      }
      RequestDispatcher ReqDis = request.getRequestDispatcher("afterBOM.jsp");
      ReqDis.forward(request, response);

    } catch (Exception ex) {
      ex.printStackTrace();

      RequestDispatcher ReqDis = request.getRequestDispatcher("Error.jsp");
      ReqDis.forward(request, response);
    }
  }
 private FileItem getParameter(List<FileItem> items, String parameterName) {
   for (FileItem item : items) {
     if (parameterName.equals(item.getFieldName())) {
       return item;
     }
   }
   return null;
 }
 /**
  * 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);
     }
   }
 }
 // for multi-values parameter (like checkbox)
 private List<FileItem> getParameters(List<FileItem> items, String parameterName) {
   List<FileItem> parameters = new ArrayList<FileItem>();
   for (FileItem item : items) {
     if (parameterName.equals(item.getFieldName())) {
       parameters.add(item);
     }
   }
   return parameters;
 }
 /**
  * Utility method to get a fileItem from a vector using the attribute name.
  *
  * @param sessionFiles
  * @param attrName
  * @return fileItem found or null
  */
 public static FileItem findItemByFieldName(List<FileItem> sessionFiles, String attrName) {
   if (sessionFiles != null) {
     for (FileItem fileItem : sessionFiles) {
       if (fileItem.getFieldName().equalsIgnoreCase(attrName)) {
         return fileItem;
       }
     }
   }
   return null;
 }
  public String validationInfo() throws Exception {
    StringBuffer stringBuffer = new StringBuffer();

    String command = (String) this.getRequestHashMap().get(GLOBALS.ADMINCOMMAND);
    if (command == null || command.compareTo(UPDATEPRODUCT) != 0) {
      return CommonSeps.getInstance().SPACE;
    }

    stringBuffer.append(new BasicItemValidation(this.itemInterface).validationInfo());

    StoreFrontInterface storeFrontInterface =
        StoreFrontFactory.getInstance(this.getWeblisketSession().getStoreName());

    String fullCategory =
        (String) URLGLOBALS.getWebappPath()
            + storeFrontInterface.getCurrentHostNamePath()
            + // storeFrontInterface.getCategoryPath() +
            this.itemInterface.getCategory();

    if (abcs.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(
        abcs.logic.communication.log.config.type.LogConfigType.VIEW)) {
      LogUtil.put(LogFactory.getInstance("Category: " + fullCategory, this, "validationInfo()"));
    }

    try {
      if (InventoryEntityFactory.getInstance()
              .getInventoryEntityInstance()
              .getItem(this.itemInterface.getId())
          == null) {
        stringBuffer.append("Item does not exist.<br>");
      }
    } catch (MoneyException e) {
      if (abcs.logic.communication.log.config.type.LogConfigTypes.LOGGING.contains(
          abcs.logic.communication.log.config.type.LogConfigType.VIEW)) {
        LogUtil.put(
            LogFactory.getInstance("Existing Item With MoneyException", this, "validationInfo()"));
      }
    }

    Object object = this.getRequestHashMap().get(BasicItemData.IMAGE);

    if (HttpFileUploadUtil.getInstance().isValid(object)) {
      FileItem fileItem = (FileItem) object;

      long size = fileItem.getSize();
      String fileName = fileItem.getName();
      String fileItemFieldName = fileItem.getFieldName();

      this.validationInfo(stringBuffer, fileName, fileItemFieldName, size);
    }

    // else stringBuffer.append("Image File Form Data Error");

    return stringBuffer.toString();
  }
  protected AttachmentResponse createBinaryAttachment(Representation representation, Task task)
      throws FileUploadException, IOException {
    RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory());
    List<FileItem> items = upload.parseRepresentation(representation);

    String name = null;
    String description = null;
    String type = null;
    FileItem uploadItem = null;

    for (FileItem fileItem : items) {
      if (fileItem.isFormField()) {
        if ("name".equals(fileItem.getFieldName())) {
          name = fileItem.getString("UTF-8");
        } else if ("description".equals(fileItem.getFieldName())) {
          description = fileItem.getString("UTF-8");
        } else if ("type".equals(fileItem.getFieldName())) {
          type = fileItem.getString("UTF-8");
        }
      } else if (fileItem.getName() != null) {
        uploadItem = fileItem;
      }
    }

    if (name == null) {
      throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }

    if (uploadItem == null) {
      throw new ActivitiIllegalArgumentException("Attachment content is required.");
    }

    Attachment createdAttachment =
        ActivitiUtil.getTaskService()
            .createAttachment(
                type, task.getId(), null, name, description, uploadItem.getInputStream());

    setStatus(Status.SUCCESS_CREATED);
    return getApplication(ActivitiRestServicesApplication.class)
        .getRestResponseFactory()
        .createAttachmentResponse(this, createdAttachment);
  }
Example #29
0
  @Post
  public Representation update(Representation entity) {
    DomRepresentation r = null;
    try {
      int userid = Integer.parseInt((String) getRequest().getAttributes().get("userid"));
      Users u = userservice.getUsers(userid);
      String fname = u.getLogo();
      // upload picture
      ResourceBundle rb = ResourceBundle.getBundle("config");
      String path = rb.getString("albumpath");
      String fileName = "";
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // Configure the factory here, if desired.
      ServletFileUpload upload = new ServletFileUpload(factory);
      // Configure the uploader here, if desired.
      List fileItems = upload.parseRequest(ServletUtils.getRequest(getRequest()));
      Iterator iter = fileItems.iterator();
      for (; iter.hasNext(); ) {
        FileItem fileItem = (FileItem) iter.next();
        if (fileItem.isFormField()) { // 当前是一个表单项
          System.out.println(
              "form field : " + fileItem.getFieldName() + ", " + fileItem.getString());
        } else {
          // 当前是一个上传的文件
          fileName = fileItem.getName();
          String extension = fileName.substring(fileName.lastIndexOf("."));
          if (fname == null || fname.equals("")) {
            Random random = new Random(10);
            int n = random.nextInt(10000);
            fileName = new Date().getTime() + "-" + n + extension;
          } else fileName = fname;
          fileItem.write(new File(path + fileName));
        }
        // 只处理第一张图片
        break;
      }

      // 生成XML表示
      r = new DomRepresentation(MediaType.TEXT_XML);
      Document doc = r.getDocument();
      Element root = doc.createElement("varkrs");
      root.setAttribute("id", "" + u.getId());
      root.setAttribute("name", u.getUsername());
      root.setAttribute("gender", "" + u.getGender());
      root.setAttribute("grade", "" + u.getGrade());
      root.setAttribute("logo", u.getLogo());
      doc.appendChild(root);
      return r;
    } catch (Exception e) {
      LogDetail.logexception(e);
      getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
      return null;
    }
  }
Example #30
0
  private String publishWeibo(List<FileItem> fileItems, String animId) {
    String userId = "";
    String type = "";
    String primaryId = "";
    String endingId = "";
    String weibo = "";

    for (int i = 0; i < fileItems.size(); i++) {
      FileItem item = fileItems.get(i);
      if (item.isFormField()) {

        if (item.getFieldName().equals("type")) {
          type = item.getString();
        }

        if (item.getFieldName().equals("userId")) {
          userId = item.getString();
        }

        if (item.getFieldName().equals("primaryId")) {
          primaryId = item.getString();
        }

        if (item.getFieldName().equals("endingId")) {
          endingId = item.getString();
        }

        if (item.getFieldName().equals("weibo")) {
          try {
            weibo = item.getString("UTF-8");
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          }
        }
      }
    } // 取参数完成

    String result = comicService.yonkomaToWeibo(userId, type, primaryId, endingId, weibo, animId);

    return result;
  }