Wiki source code of FileUploadGroovy

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

Show last authors
1 /*
2 #**
3 * Groovy script allowing to add a file upload attachment to a document
4 *
5 *#
6 */
7 // {code}
8 import com.xpn.xwiki.doc.*;
9 import com.xpn.xwiki.*;
10 import com.xpn.xwiki.util.Util;
11 import java.io.*;
12 import java.util.*;
13
14 public class FileUpload {
15 /*
16 #**
17 * Groovy script allowing to add a file upload attachment to a document
18 * @param doc1 Document to attach file uploads to ($doc from velocity)
19 * @param context1 Context ($context from velocity)
20 * @return returns the number of attachments or -10 if missing programming rights
21 *#
22 */
23 public int addAttachments(doc1, context1) {
24 def doc = doc1.document;
25 if (!context1.hasProgrammingRights())
26 return -10;
27 def context = context1.context;
28 if (context==null)
29 return -10;
30 def xwiki = context.getWiki();
31 int nb = 0;
32 def fileupload = xwiki.getPlugin("fileupload",context)
33 for (fileitem in fileupload.getFileItems(context)) {
34 if (!fileitem.isFormField()) {
35 def name = fileitem.fieldName
36 byte[] data = fileupload.getFileItemData(name, context);
37 if ((data!=null)&&(data.length>0)) {
38 String fname = fileupload.getFileName(name, context);
39 int i = fname.lastIndexOf("\\");
40 if (i==-1)
41 i = fname.lastIndexOf("/");
42 def filename = fname.substring(i+1);
43 filename = filename.replaceAll("\\+"," ");
44 def attachment = doc.getAttachment(filename);
45 if (attachment==null) {
46 attachment = new XWikiAttachment();
47 doc.getAttachmentList().add(attachment);
48 // Add the attachment to the document
49 attachment.setDoc(doc);
50 }
51 attachment.setContent(data);
52 attachment.setFilename(filename);
53 // TODO: handle Author
54 attachment.setAuthor(context1.user);
55 doc.saveAttachmentContent(attachment, context);
56 nb++;
57 }
58 }
59 }
60 return nb;
61 }
62 }
63 // {code}