FileUploadGroovy

Last modified by Ludovic Dubost on 2008/09/05 10:37

/* Failed to execute the [velocity] macro. Cause: [The execution of the [velocity] script macro is not allowed in [ludovic:Code.FileUploadGroovy]. Check the rights of its last author or the parameters if it's rendered from another script.]. Click on this message for details.
*/ // 

import com.xpn.xwiki.doc.*;
import com.xpn.xwiki.*;
import com.xpn.xwiki.util.Util;
import java.io.*;
import java.util.*;

public class FileUpload {
/*
#**
* Groovy script allowing to add a file upload attachment to a document
* @param doc1 Document to attach file uploads to ($doc from velocity)
* @param context1 Context ($context from velocity)
* @return returns the number of attachments or -10 if missing programming rights
*#
*/
public int addAttachments(doc1, context1) {
      def doc = doc1.document;
      if (!context1.hasProgrammingRights())
        return -10;
      def context = context1.context;
      if (context==null)
       return -10;
      def xwiki = context.getWiki();
      int nb = 0;
      def fileupload = xwiki.getPlugin("fileupload",context)
      for (fileitem in fileupload.getFileItems(context)) {
       if (!fileitem.isFormField()) {
       def name = fileitem.fieldName
        byte[] data = fileupload.getFileItemData(name, context);
       if ((data!=null)&&(data.length>0)) {
        String fname = fileupload.getFileName(name, context);
       int i = fname.lastIndexOf("\\");
       if (i==-1)
           i = fname.lastIndexOf("/");
       def filename = fname.substring(i+1);
        filename = filename.replaceAll("\\+"," ");
       def attachment = doc.getAttachment(filename);
       if (attachment==null) {
          attachment = new XWikiAttachment();
          doc.getAttachmentList().add(attachment);
         // Add the attachment to the document
          attachment.setDoc(doc);
        }
        attachment.setContent(data);
        attachment.setFilename(filename);
       // TODO: handle Author
        attachment.setAuthor(context1.user);
        doc.saveAttachmentContent(attachment, context);
        nb++;
         }
        }
       }
     return nb;
     }
}
//