mercredi 9 novembre 2011

How to upload a file using SiteBricks ?

It is supposed to work that way :
@Post
public Reply<?> upload(Request req) {
 try {
  File tmp = File.createTempFile("upload", ".csv");
  OutputStream out = new FileOutputStream(tmp);
  req.readTo(out);
  out.close();
    
  // do something with tmp
   
 }
 catch (IOException e) {
  e.printStackTrace();
 }
 
 return Reply.saying().ok();
}
But in fact the tmp File will not only contain the sent file but also all the request details (User Agent, others parameters, ...). As I needed a way to have the sent file and only it, I did it with a more regular Servlet Way. First add the commons-fileupload to your path.

<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.2.2</version>
</dependency>
Then Inject the HttpServletRequest in your @Show or @Service class.
@Inject
private HttpServletRequest request;
Finaly, use the commons-fileupload methods to get your file :

try {
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 if(isMultipart) {
  ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
  List items = upload.parseRequest(request);
  for(Object obj : items) {
   if(obj instanceof FileItem) {
    FileItem item = (FileItem)obj;
    if(item.getFieldName().equals("my-file-field-name")) {
     // do something with item.getInputStream()
    }
   }

  }
 }
}
catch(FileUploadException e) {
 e.printStackTrace();
}
catch (IOException e) {
 e.printStackTrace();
}

2 commentaires:

  1. Nice.

    Btw you dont need to make a field for HttpServletRequest you can inject it directly into the @Post method (same for any Guice object).

    Dhanji.

    RépondreSupprimer