コード例 #1
0
  /**
   * 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);
  }
コード例 #2
0
  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;
  }
コード例 #3
0
  /**
   * @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$
    }
  }
コード例 #4
0
 protected String getValue(FileItem item, ServletRequest request) {
   String encoding = request.getCharacterEncoding();
   if (!isNullOrEmpty(encoding)) {
     try {
       return item.getString(encoding);
     } catch (UnsupportedEncodingException e) {
       logger.warn("Request have an invalid encoding. Ignoring it");
     }
   }
   return item.getString();
 }
コード例 #5
0
ファイル: AlterCityServlet.java プロジェクト: wujunwei/Treval
  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");
      }
    }
  }
コード例 #6
0
ファイル: ApiAdaptor.java プロジェクト: liumingli/comicdiy
  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;
  }
  /**
   * 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;
  }
コード例 #8
0
ファイル: Adapter.java プロジェクト: zenframework/z8
  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());
  }
コード例 #9
0
  /**
   * @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();
    }
  }
コード例 #10
0
ファイル: ApiAdaptor.java プロジェクト: liumingli/comicdiy
  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;
  }
コード例 #11
0
 /**
  * Extracts the XML string associated with an uploaded multipath file item.
  *
  * @return the XML string (null if none)
  * @throws UnsupportedEncodingException (should never be thrown)
  */
 private String extractItemXml(FileItem item) throws UnsupportedEncodingException {
   String xml = null;
   if (item != null) {
     xml = Val.chkStr(Val.removeBOM(item.getString("UTF-8")));
   }
   return xml;
 }
コード例 #12
0
  @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);
    }
  }
コード例 #13
0
ファイル: BXServletRequest.java プロジェクト: phspaelti/basex
 @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);
   }
 }
コード例 #14
0
  /** @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);
    }
  }
コード例 #15
0
ファイル: ProxyServlet.java プロジェクト: alesj/hawtio
 /**
  * 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);
   }
 }
コード例 #16
0
	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;
	}
コード例 #17
0
 /** Returns the contents of the uploaded file as a String, using the specified encoding. */
 public String getString(String encoding) {
   try {
     return fileItem.getString(encoding); // throws UnsupportedEncodingException
   } catch (Exception e) {
     throw new RuntimeException("Getting contents of uploaded file failed (" + this + ")", e);
   }
 }
コード例 #18
0
 private String getParameterValue(List<FileItem> items, String parameterName) {
   SilverTrace.debug(
       "form",
       "XmlSearchForm.getParameterValue",
       "root.MSG_GEN_ENTER_METHOD",
       "parameterName = " + parameterName);
   FileItem item = getParameter(items, parameterName);
   if (item != null && item.isFormField()) {
     SilverTrace.debug(
         "form",
         "XmlSearchForm.getParameterValue",
         "root.MSG_GEN_EXIT_METHOD",
         "parameterValue = " + item.getString());
     return item.getString();
   }
   return null;
 }
コード例 #19
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      ArrayList<String> array = new ArrayList<>();
      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
      if (isMultipart) {
        FileItemFactory fit = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fit);
        File savePath = null;
        try {
          List<FileItem> ft = upload.parseRequest(request);
          for (FileItem f : ft) {
            if (!f.isFormField()) {
              String n = new File(f.getName()).getName();
              savePath =
                  new File(
                      request.getServletContext().getRealPath("/")
                          + "images/"
                          + System.currentTimeMillis()
                          + "_"
                          + n);
              f.write(savePath);
              array.add(savePath.getName());
            }
            /** file upload ends */

            /** Start Get data from <inputs> */
            if (f.isFormField()) {
              String value = f.getString();
              array.add(value);
            }
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (array.get(0).toString().equals("addHotelPic")) {
        model.pojo.HotelPictures hotel_pictures = new model.pojo.HotelPictures();
        model.pojo.ActionStatus action_status =
            (model.pojo.ActionStatus)
                model.DbManager.getInstance().retrieveDataById(model.pojo.ActionStatus.class, 6);
        model.pojo.Hotel hotel =
            (model.pojo.Hotel)
                model.DbManager.getInstance()
                    .retrieveDataById(model.pojo.Hotel.class, Integer.parseInt(array.get(1)));

        hotel_pictures.setActionStatus(action_status);
        hotel_pictures.setHotel(hotel);
        hotel_pictures.setUrl(array.get(2).toString());

        model.DbManager.getInstance().saveData(hotel_pictures);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #20
0
  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;
    }
  }
コード例 #21
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);
     }
   }
 }
コード例 #22
0
  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);
  }
コード例 #23
0
ファイル: UsersResource.java プロジェクト: flacro/photowall
  @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;
    }
  }
コード例 #24
0
ファイル: ApiAdaptor.java プロジェクト: liumingli/comicdiy
  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;
  }
コード例 #25
0
  /**
   * Pseudo-constructor that allows the class to perform any initialization necessary.
   *
   * @param request an HttpServletRequest that has a content-type of multipart.
   * @param tempDir a File representing the temporary directory that can be used to store file parts
   *     as they are uploaded if this is desirable
   * @param maxPostSize the size in bytes beyond which the request should not be read, and a
   *     FileUploadLimitExceeded exception should be thrown
   * @throws IOException if a problem occurs processing the request of storing temporary files
   * @throws FileUploadLimitExceededException if the POST content is longer than the maxPostSize
   *     supplied.
   */
  @SuppressWarnings("unchecked")
  public void build(HttpServletRequest request, File tempDir, long maxPostSize)
      throws IOException, FileUploadLimitExceededException {
    try {
      this.charset = request.getCharacterEncoding();
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setRepository(tempDir);
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setSizeMax(maxPostSize);
      List<FileItem> items = upload.parseRequest(request);
      Map<String, List<String>> params = new HashMap<String, List<String>>();

      for (FileItem item : items) {
        // If it's a form field, add the string value to the list
        if (item.isFormField()) {
          List<String> values = params.get(item.getFieldName());
          if (values == null) {
            values = new ArrayList<String>();
            params.put(item.getFieldName(), values);
          }
          values.add(charset == null ? item.getString() : item.getString(charset));
        } // Else store the file param
        else {
          files.put(item.getFieldName(), item);
        }
      }

      // Now convert them down into the usual map of String->String[]
      for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        List<String> values = entry.getValue();
        this.parameters.put(entry.getKey(), values.toArray(new String[values.size()]));
      }
    } catch (FileUploadBase.SizeLimitExceededException slee) {
      throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize());
    } catch (FileUploadException fue) {
      IOException ioe = new IOException("Could not parse and cache file upload data.");
      ioe.initCause(fue);
      throw ioe;
    }
  }
コード例 #26
0
  @SuppressWarnings("unchecked")
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    ServletFileUpload servletFileUpload = setUpServletFileUpload();
    ContestManager contestManager = SessionUtil.getInstance().getContestManager();

    List<FileItem> fileItemsList = null;
    try {
      fileItemsList = servletFileUpload.parseRequest(request);
    } catch (FileUploadException e) {
      setError(
          request,
          response,
          "File upload did not finish successfully.  Or you might be using an unsupported browser.");
      return;
    }

    InputStream inputStream = null;
    Map<String, String> fieldValues = new HashMap<String, String>();
    for (FileItem fileItem : fileItemsList) {
      if (fileItem.isFormField()) {
        fieldValues.put(fileItem.getFieldName(), fileItem.getString());
      } else {
        inputStream = fileItem.getInputStream();
        break;
      }
    }
    if (inputStream == null) {
      setError(request, response, "No file seems to be uploaded.");
      return;
    }
    Task task = getTastInfo(fieldValues, contestManager);
    if (task == null) {
      setError(request, response, "Error reading task infomation.");
      return;
    }
    try {
      List<String> messages =
          unzipStream(
              request, response, inputStream, task, contestManager, fieldValues.get("contestId"));
      request.getSession().setAttribute("messages", messages);
    } finally {
      try {
        inputStream.close();
      } catch (IOException e) {
      }
    }
    response.sendRedirect(
        "editTask?contestId=" + fieldValues.get("contestId") + "&taskId=" + task.getId());
  }
コード例 #27
0
ファイル: Util.java プロジェクト: redmouse/management
  public String getParameterEnctypeMultipart(
      String parameter, HttpServletRequest request, ServletFileUpload upload) throws Exception {
    List items = upload.parseRequest(request);
    Iterator it = items.iterator();

    while (it.hasNext()) {
      FileItem item = (FileItem) it.next();
      if (item.isFormField() && item.getFieldName().equals(parameter)) {
        return item.getString("UTF-8");
      }
    }
    return "";
  }
コード例 #28
0
  @Override
  public Template handleRequest(
      HttpServletRequest request, HttpServletResponse response, Context context) {

    // process only if its multipart content
    context.put("apptitle", "E-com Journal");
    String TemplateTitle = null;

    System.out.println("UPLOAD SERVLET Template title :" + TemplateTitle);
    Template template = null;
    try {

      HttpSession session = request.getSession();
      String UserRole = (String) session.getAttribute("userRole");
      System.out.println(UserRole);
      String name = null;
      if (UserRole == "Editor") {

        if (ServletFileUpload.isMultipartContent(request)) {
          try {
            List<FileItem> multiparts =
                new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
              if (!item.isFormField()) {
                name = new File(item.getName()).getName();
                item.write(new File(UPLOAD_DIRECTORY + name));
                System.out.println("name: of file:" + name);
              } else {
                TemplateTitle = item.getString();
              }
            }
            UploadModel uc = new UploadModel();
            uc.setFilePath(UPLOAD_DIRECTORY + name, TemplateTitle);
            // File uploaded successfully
            context.put("message", "File Uploaded Successfully");
            System.out.println("File Uploaded Successfully");

          } catch (Exception ex) {
            context.put("message", "File Upload Failed due to " + ex);
            System.out.println("File Upload Failed due to ");
          }
        }
      }
      template = getTemplate("/forms/upload.vm");
    } catch (Exception e) {
      e.printStackTrace();
    }
    return template;
  }
コード例 #29
0
  private void processNormalFormField(FileItem item, String charset)
      throws UnsupportedEncodingException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Item is a normal form field");
    }
    List<String> values;
    if (params.get(item.getFieldName()) != null) {
      values = params.get(item.getFieldName());
    } else {
      values = new ArrayList<String>();
    }

    // note: see http://jira.opensymphony.com/browse/WW-633
    // basically, in some cases the charset may be null, so
    // we're just going to try to "other" method (no idea if this
    // will work)
    if (charset != null) {
      values.add(item.getString(charset));
    } else {
      values.add(item.getString());
    }
    params.put(item.getFieldName(), values);
  }
コード例 #30
0
  /**
   * Adds a regular text parameter to the set of text parameters for this request. Handles the case
   * of multiple values for the same parameter by using an array for the parameter value.
   *
   * @param request The request in which the parameter was specified.
   * @param item The file item for the parameter to add.
   */
  public void addTextParameter(RequestWrapper request, FileItem item) {

    String name = item.getFieldName();
    String value = null;
    boolean haveValue = false;
    String encoding = request.getCharacterEncoding();

    if (encoding != null) {
      try {
        value = item.getString(encoding);
        haveValue = true;
      } catch (Exception e) {
        // Handled below, since haveValue is false.
      }
    }
    if (!haveValue) {
      try {
        value = item.getString("ISO-8859-1");
      } catch (java.io.UnsupportedEncodingException uee) {
        value = item.getString();
      }
      haveValue = true;
    }

    String[] oldArray = (String[]) request.getParameterValues(name);
    String[] newArray;

    if (oldArray != null) {
      newArray = new String[oldArray.length + 1];
      System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
      newArray[oldArray.length] = value;
    } else {
      newArray = new String[] {value};
    }

    request.addParameter(name, newArray);
  }