Thursday, October 11, 2012

Custom File Upload in the xPage. Java. Backend.

There are a lot of articles about custom file upload with xPages. Most of them are about JavaScript. They use Java classes, so convert that code in to the Java is not problematic.

It's very easy to do in backend java code within xPages. The only one miss is that we could not write to the file attachment directly from the request. We still need to use a file. Thanks to xPage - it handle server temp files himself.

The code:

public void process() throws Exception {
 HttpServletRequest request = getRequest();
 
 Document document =
  getEs().createDocument().getDocument();
 document.replaceItemValue("Form", "picture");

 Map parameters = request.getParameterMap();
 UploadedFile uploadedFile=
  (UploadedFile) parameters.get("upload");
 document.replaceItemValue(
  "FileName",
  uploadedFile.getClientFileName());
 
 File tmpFile = uploadedFile.getServerFile();
 File fileToUpload = new File(
   tmpFile.getParentFile().getAbsolutePath().
   concat(java.io.File.separator).
   concat(uploadedFile.getClientFileName())); 
 
 boolean success = tmpFile.renameTo(fileToUpload); 
 addAttachment(document, success?fileToUpload:tmpFile);
 fileToUpload.renameTo(tmpFile);
 
 document.save(true, true);
}

private void addAttachment(Document document, File file)
 throws Exception{
 RichTextItem item = document.createRichTextItem("Body");
 item.embedObject(
  EmbeddedObject.EMBED_ATTACHMENT,
  "", 
  file.getCanonicalPath(), null);   
}

Look http://lotusandjava.blogspot.com/2012/09/accessing-xpages-global-objects-in-java.html to find how to get request

No comments: