Expand my Community achievements bar.

Learn about Edge Delivery Services in upcoming GEM session
SOLVED

How to create File Object in AEM if using apache http client to post file to AEM

Avatar

Former Community Member

Hi there,

I have a case that it need to use apache http client to post file(e.g., XML file format) to AEM. Below is client code snippet :

public void SubmitPost(String url, String filename, String filepath) { HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost(url); FileBody bin = new FileBody(new File(filepath + File.separator + filename)); StringBody comment = new StringBody(filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("filename", comment); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { System.out.println("Server response Okey....."); HttpEntity resEntity = response.getEntity(); System.out.println(EntityUtils.toString(resEntity)); System.out.println(resEntity.getContent()); EntityUtils.consume(resEntity); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { } } }

But i wondering how to program the server and create a java File object since need to use SlingHttpServletRequest also read the file data. Anyone had ever experience it? Please comment on it。

public class HandleFile extends org.apache.sling.api.servlets.SlingAllMethodsServlet { private static final long serialVersionUID = 2598426539166789515L; private Session session; /** Default log. */ protected final Logger log = LoggerFactory.getLogger(this.getClass()); // Inject a Sling ResourceResolverFactory @Reference private ResourceResolverFactory resolverFactory; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException { //TODO //To create file Object here so that read it }

 

Thanks a lot in advance.

 

Best regards,

Brian

1 Accepted Solution

Avatar

Correct answer by
Level 4
4 Replies

Avatar

Correct answer by
Level 4

Avatar

Former Community Member

hi sumit, i saw that aritcle before. And this post target is how to create Java File Object in AEM since i need to use File Object to another function.

thanks for your comment.

Avatar

Level 10

In the above artilce - it shows you how to get an InputStream from the posted file (exactly what you are asking for). Once you get the InputStream - you can easily create a file using Java in your OSGi bundle:

http://www.mkyong.com/java/how-to-convert-inputstream-to-file-in-java/

Avatar

Former Community Member

Great, it is just fit to my need. Thanks for your reply.