Expand my Community achievements bar.

SOLVED

AEM File Upload

Avatar

Level 1

I have deployed osgi bundle to AEM 6.2 and calling sling servlet from java class as post request. But request is not passed to sling servlet.

Example : Adobe Experience Manager Help | Automating the process of uploading multiple digital assets to the A...

Need help how can I call post method of sling servlet from java class.

1 Accepted Solution

Avatar

Correct answer by
Level 10

I just tested this with AEM 6.2 - App:

ADAM.png

Successfully posted these file to the DAM via a Servlet that uses the Asset-manager API:

AADAM.png

View solution in original post

6 Replies

Avatar

Level 10

that article shows you how to post from a Java client using Java logic to an AEM Sling Servlet that uses the AssetManager API:

//Read the File from the File System

  File myFile = new File(fileLocation+fileName);

              

               org.apache.http.entity.mime.MultipartEntity entity = new org.apache.http.entity.mime.MultipartEntity ();

               byte[] b = new byte[(int)myFile.length()];

               org.apache.http.entity.mime.content.FileBody fileBody = new org.apache.http.entity.mime.content.FileBody(myFile, mimeType) ;

               org.apache.http.entity.mime.content.StringBody imageTitle = new org.apache.http.entity.mime.content.StringBody(path);

               entity.addPart("imageTitle", imageTitle);

               entity.addPart("image", fileBody);

               post.setEntity(entity);

  

               org.apache.http.impl.client.DefaultHttpClient client = new org.apache.http.impl.client.DefaultHttpClient();

               org.apache.http.HttpResponse response = null;

               response = client.execute(post);

See this blog - you can watch video too and see it working:

Scott's Digital Community: Automating the process of uploading multiple digital assets to the Adobe ...

Avatar

Level 10

Set a breakpoint in the Java code and let us know what is happening. You may have the wrong URL or something like that. But i suggest watching the video and see it working.

Avatar

Correct answer by
Level 10

I just tested this with AEM 6.2 - App:

ADAM.png

Successfully posted these file to the DAM via a Servlet that uses the Asset-manager API:

AADAM.png

Avatar

Level 1

Hi,

Please find my code below,

Local ::

// Posts the selected file to AEM
private static void postAEM(File file, String host, String path, String mimeType) {
  try {

   String aemPostUrl = host + "/bin/upmanydamfiles";
   System.out.println("AEM HOST :: "+ aemPostUrl);
   HttpPost post = new HttpPost(aemPostUrl);
  

   org.apache.http.entity.mime.MultipartEntity entity = new org.apache.http.entity.mime.MultipartEntity();
   byte[] b = new byte[(int) file.length()];
   org.apache.http.entity.mime.content.FileBody fileBody = new org.apache.http.entity.mime.content.FileBody(file, mimeType);
   org.apache.http.entity.mime.content.StringBody filePath = new org.apache.http.entity.mime.content.StringBody(path);

   entity.addPart("filePath", filePath);
   entity.addPart("fileBody", fileBody);
   post.setEntity(entity);

   org.apache.http.impl.client.DefaultHttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
   org.apache.http.HttpResponse response = null;
   System.out.println("Calling sling servlet from postAEM()..................");
   response = client.execute(post);

   System.out.println("Done");
  } catch (Exception e) {
   e.printStackTrace();
  }

}

Console output :: AEM HOST :: http://dev1.company.com/bin/upmanydamfiles
Calling sling servlet from postAEM()..................
Done

Sling servlet deployed on AEM ::

@SlingServlet(paths="/bin/upmanydamfiles", methods = "POST", metatype=true)
public class HandleFile extends SlingAllMethodsServlet {
private static final long serialVersionUID = 2598426539166789515L;
private Session session;
private String clientLibPath = "";

protected final Logger log = LoggerFactory.getLogger(getClass());

private ResourceResolverFactory resolverFactory;

public HandleFile() {
}

protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
   throws ServerException, IOException {
}

protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
   throws ServerException, IOException {
  try {
   log.info("Inside doPost method of HandleFile...");
   // boolean isMultipart =
   // ServletFileUpload.isMultipartContent(request);
   PrintWriter out = null;
   int index = 1;

   out = response.getWriter();
   // if (isMultipart) {
   Map<String, RequestParameter[]> params = request.getRequestParameterMap();
   log.info("Params fetched from request......");
   for (Map.Entry<String, RequestParameter[]> pairs : params.entrySet()) {
    String k = (String) pairs.getKey();

    RequestParameter[] pArr = (RequestParameter[]) pairs.getValue();

    RequestParameter param0 = pArr[0];

    boolean formField = param0.isFormField();

    if (formField) {
     String libLoc = param0.getString();
     clientLibPath = libLoc;
    } else {
     InputStream stream = param0.getInputStream();
     String mimeType = param0.getContentType();
     log.info("THE CONTENT TYPE IS: " + mimeType);
     log.info("Writting content to location :" + clientLibPath);
     writeToClientLib(stream, param0.getFileName(), clientLibPath, mimeType);
     log.info("Asset created at location:: " + clientLibPath);
    }
    index++;
   }
   // }
  } catch (Exception e) {
   int index;
   e.printStackTrace();
  }
}

private String writeToClientLib(InputStream is, String fileName, String path, String mimetype) {
  try {
   log.info("Inside writeToClientLib method of HandleFile......");

   ResourceResolver resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
   AssetManager assetMgr = (AssetManager) resourceResolver.adaptTo(AssetManager.class);
   String newFile = path + fileName;
   log.info("Creating asset in AEM......");
   assetMgr.createAsset(newFile, is, mimetype, true);
   return newFile;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
}

protected void bindResolverFactory(ResourceResolverFactory paramResourceResolverFactory) {
  resolverFactory = paramResourceResolverFactory;
}

protected void unbindResolverFactory(ResourceResolverFactory paramResourceResolverFactory) {
  if (resolverFactory == paramResourceResolverFactory) {
   resolverFactory = null;
  }
}

When I check in AEM content location, I am not able to find the file. I have also configured logger for bundle that is deployed on AEM but nothing found in logger.

Please guide for the same.

Avatar

Level 10

WHen writing Sling Servlets to handle files - you need to use this app Java logic:

@Override

protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {

        

      try

         {

         final boolean isMultipart = org.apache.commons.fileupload.servlet.ServletFileUpload.isMultipartContent(request);

         PrintWriter out = null;

         int index = 1 ;

          

           out = response.getWriter();

           if (isMultipart) {

             final java.util.Map<String, org.apache.sling.api.request.RequestParameter[]> params = request.getRequestParameterMap();

             

             for (final java.util.Map.Entry<String, org.apache.sling.api.request.RequestParameter[]> pairs : params.entrySet()) {

               

                 final String k = pairs.getKey();

               

                 final org.apache.sling.api.request.RequestParameter[] pArr = pairs.getValue();

               

                 final org.apache.sling.api.request.RequestParameter param0 = pArr[0];

                 

                 //Determine if the posted value is a file or the JCR Path

                 boolean formField = param0.isFormField(); //Is this a form field or a posted file

                 

                 if (formField)

                 {

                     String libLoc = param0.getString(); 

                     clientLibPath = libLoc ; //Set the class member - its the first posted value from the client

                     log.info("FIELD VALUE IS: "+libLoc )  ;

                     

                 }

                 else

                 {

                     // final org.apache.sling.api.request.RequestParameter param1 = pArr[1];

                  final InputStream stream = param0.getInputStream();

                  String mimeType = param0.getContentType();

               

                  log.info("THE CONTENT TYPE IS: "+mimeType )  ;

                  

                  //Save the uploaded file into the Adobe CQ DAM

                  writeToClientLib(stream,param0.getFileName(),clientLibPath,mimeType  );

                 }

                 index ++;

             }

           }

         }

          

         catch (Exception e) {

             e.printStackTrace();

         }

      

     }

Avatar

Level 1

Hi,

This has been already implemented in sling servlet but it is still not working for me.

I have configured log file in AEM but no log has been captured in that. Can you let me know how can I get the logs of sling servlet deployed in AEM ?

log.png

Thanks,

Darshan