Ejemplo n.º 1
0
  /**
   * Call this method as the first action in your servlet, to ensure that the files are technically
   * handled, before your business logic takes places. This method should only be invoked for POST
   * calls.
   *
   * @param aRequestScope Current request scope
   * @throws FileUploadException
   */
  public static void handleUpload(@Nonnull final IRequestWebScopeWithoutResponse aRequestScope)
      throws FileUploadException {
    s_aLogger.info("handleUpload");
    // get the upload ID that was sent via a hidden field from the upload frame
    final String sUploadID = aRequestScope.getAttributeAsString(PARAM_UPLOAD_ID);
    if (StringHelper.hasNoText(sUploadID)) {
      FileUploadProgressListener.getInstance().reset();
      throw new FileUploadException("Unable to retrieve upload ID for received request!");
    }

    // Check if we have the matching upload context
    final UploadContext aContext = UploadContextRegistry.getInstance().getContext(sUploadID);
    if (aContext == null) {
      FileUploadProgressListener.getInstance().reset();
      throw new FileUploadException(
          "Unable to retrieve upload context for received request with ID '" + sUploadID + "'!");
    }
    // Ensure that the upload directory exists
    final File aUploadDir = aContext.getUploadDirectory();
    if (!aUploadDir.exists()) {
      final FileIOError aErr = FileOperations.createDirRecursive(aUploadDir);
      if (aErr.isFailure()) {
        FileUploadProgressListener.getInstance().reset();
        throw new FileUploadException(
            "Failed to create upload directory "
                + aUploadDir
                + ": "
                + aErr.toString()); // $NON-NLS-2$
      }
    }

    for (final IFileItem aFileItem : aRequestScope.getAllUploadedFileItemValues()) {
      final File aUploadedFile = _handleUploadFileItem(aFileItem, aContext);
      if (aUploadedFile != null) {
        FileUploadProgressListener.getInstance()
            .setFileName(FilenameHelper.getRelativeToParentDirectory(aUploadedFile, aUploadDir));
      }
    }
    FileUploadProgressListener.getInstance().setUploadFinished();
  }