Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (C) 2014-2015 Philip Helger (www.helger.com) philip[at]helger[dot]com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package com.helger.webbasics.servlet;
 
 
 
 
A special upload servlet to be used with FineUploader.

Author(s):
Philip Helger
 
 {
   public static final String SERVLET_DEFAULT_NAME = "userUpload";
   public static final String SERVLET_DEFAULT_PATH = '/' + ;
   public static final String PARAM_DIRECTORY = "dir";
   public static final String PARAM_ID = "id";
   public static final String PARAM_FILE = "file";
 
   private static final Logger s_aLogger = LoggerFactory.getLogger (UserUploadServlet.class);
 
   @Override
   @Nonnull
   {
     return ;
   }
 
   @Nonnull
   protected IJsonObject createSuccess ()
   {
     return new JsonObject ().add ("success"true);
   }
 
   @Nonnull
   protected IJsonObject createError (@Nonnull final String sErrorMsg)
   {
     .error ("User upload error: " + sErrorMsg);
     return new JsonObject ().add ("success"false).add ("error"sErrorMsg).add ("preventRetry"true);
   }
 
   private void _post (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope,
                       @Nonnull final UnifiedResponse aUnifiedResponse)
   {
     IJsonObject ret;
 
     final Object aFile = aRequestScope.getAttributeObject ();
     if (!(aFile instanceof IFileItem))
     {
       ret = createError ("No file passed. Maybe the request is not multipart, put 'multipart/form-data' enctype for your form.");
     }
     else
     {
       final IFileItem aFileItem = (IFileItemaFile;
       final String sDirectory = aRequestScope.getAttributeAsString ();
       final boolean bDirectoryPresent = StringHelper.hasText (sDirectory);
       if (bDirectoryPresent && !FilenameHelper.isValidFilenameWithPaths (sDirectory))
         ret = createError ("The passed directory name '" + sDirectory + "' is invalid!");
       else
       {
         final String sID = aRequestScope.getAttributeAsString ();
         if (StringHelper.hasNoText (sID))
          ret = createError ("No file ID passed!");
        else
        {
          .info ("Uploading " + aFileItem + " as " + sID + " to " + sDirectory);
          // Directory
          String sPath = bDirectoryPresent ? FilenameHelper.ensurePathEndingWithSeparator (sDirectory) : "/";
          // Add basename
          sPath += GlobalIDFactory.getNewPersistentStringID ();
          // Add extension
          final String sExt = FilenameHelper.getExtension (aFileItem.getName ());
          if (StringHelper.hasText (sExt))
            sPath += "." + sExt;
          final UserDataObject aUDO = new UserDataObject (sPath);
          try
          {
            if (aFileItem.write (aUDO.getAsFile ()).isFailure ())
            {
              ret = createError ("Failed to store uploaded file " + aFileItem + " to " + aUDO);
            }
            else
            {
              // Add to manager
              UserUploadManager.getInstance ().addUploadedFile (sIDaUDO);
              ret = createSuccess ();
            }
          }
          catch (final Exception ex)
          {
            .error ("Writing " + aFileItem + " to " + aUDO + " failed"ex);
            ret = createError ("Failed to store uploaded file " + aFileItem + " to " + aUDO);
          }
        }
      }
    }
    aUnifiedResponse.setMimeType (.).setContentAndCharset (JsonWriter.getAsString (ret),
                                                                                    .);
  }
  protected void handleRequest (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope,
                                @Nonnull final UnifiedResponse aUnifiedResponsethrows ServletExceptionIOException
  {
    aUnifiedResponse.disableCaching ();
    _post (aRequestScopeaUnifiedResponse);
  }
New to GrepCode? Check out our FAQ X