コード例 #1
0
  /**
   * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
   * multipart classes (see class description).
   *
   * @param saveDir the directory to save off the file
   * @param servletRequest the request containing the multipart
   * @throws java.io.IOException is thrown if encoding fails.
   */
  @SuppressWarnings("unchecked")
  @Override
  public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
      fac.setRepository(new File(saveDir));
    }

    ProgressMonitor monitor = null;
    // Parse the request
    try {
      ServletFileUpload upload = new ServletFileUpload(fac);
      upload.setSizeMax(maxSize);

      monitor = new ProgressMonitor();
      upload.setProgressListener(monitor);
      servletRequest.getSession().setAttribute(ProgressMonitor.SESSION_PROGRESS_MONITOR, monitor);

      List<FileItem> items = upload.parseRequest(createRequestContext(servletRequest));

      for (FileItem item1 : items) {
        FileItem item = item1;

        if (log.isDebugEnabled()) {
          log.debug("Found item " + item.getFieldName());
        }
        if (item.isFormField()) {
          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)
          String charset = servletRequest.getCharacterEncoding();
          if (charset != null) {
            values.add(item.getString(charset));
          } else {
            values.add(item.getString());
          }
          params.put(item.getFieldName(), values);
        } else {
          if (log.isDebugEnabled()) {
            log.debug("Item is a file upload");
          }
          List<FileItem> values;
          if (files.get(item.getFieldName()) != null) {
            values = files.get(item.getFieldName());
          } else {
            values = new ArrayList<FileItem>();
          }

          values.add(item);
          files.put(item.getFieldName(), values);
        }
      }
    } catch (FileUploadException e) {
      e.printStackTrace();
      if (monitor != null) monitor.abort();
      log.error(e);
      errors.add(e.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      if (monitor != null) monitor.abort();
    }
  }