如何通过XPages Java Bean上传和保存附件


问题内容

我了解了如何使用表达式语言将XPages控件绑定到Java Bean。然后,它会自动访问setter和getter。

但是,如何处理文件附件?

看起来像什么?我希望能够将文件上传控件绑定到Bean。将附件保存到“任何”文档中…无论是当前文档还是外部文档,bean都应能够处理该逻辑。

我想我不知道如何将文件附件放入内存bean中,以便能够执行任何操作,例如保存到文档中。

任何意见,将不胜感激。

谢谢!


问题答案:

您需要使用 com.ibm.xsp.component.UIFileuploadEx.UploadedFile 类在Bean中创建吸气剂和吸气剂:

private UploadedFile uploadedFile;

public UploadedFile getFileUpload() {
    return uploadedFile;
}
public void setFileUpload( UploadedFile to ) {
    this.uploadedFile = to;
}

在处理Bean数据的函数中(例如,保存函数),可以通过检查对象是否为空来检查文件是否已上传。如果不为null,则上传文件。

要处理该上载的文件,请首先使用getServerFile()方法获取 com.ibm.xsp.http.IUploadedFile
对象的实例。该对象具有getServerFile()方法,该方法返回上载文件的File对象。该对象的问题在于它具有一个隐秘的名称(可能要处理多个人同时上传具有相同名称的文件)。可以使用IUploadedFile类的
getClientFileName() 方法检索原始文件名。

然后,我倾向于将重命名文件重命名为其原始文件名,进行处理(将其嵌入到RTF中或对其进行其他处理),然后将其重命名为其原始(重命名)。最后一步很重要,因为只有在代码完成后才清理(删除)文件。

这是上述步骤的示例代码:

import java.io.File;
import com.ibm.xsp.component.UIFileuploadEx.UploadedFile;
import com.ibm.xsp.http.IUploadedFile;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.RichTextItem;
import com.ibm.xsp.extlib.util.ExtLibUtil;  //only used here to get the current db

public void saveMyBean() {

  if (uploadedFile != null ) {

        //get the uploaded file
        IUploadedFile iUploadedFile = uploadedFile.getUploadedFile();

        //get the server file (with a cryptic filename)
        File serverFile = iUploadedFile.getServerFile();

        //get the original filename
        String fileName = iUploadedFile.getClientFileName();

        File correctedFile = new File( serverFile.getParentFile().getAbsolutePath() + File.separator + fileName );

        //rename the file to its original name
        boolean success = serverFile.renameTo(correctedFile);

        if (success) {
            //do whatever you want here with correctedFile

            //example of how to embed it in a document:
            Database dbCurrent = ExtLibUtil.getCurrentDatabase();
            Document doc = dbCurrent.createDocument();
            RichTextItem rtFiles = doc.createRichTextItem("files");
            rtFiles.embedObject(lotus.domino.EmbeddedObject.EMBED_ATTACHMENT, "", correctedFile.getAbsolutePath(), null);
            doc.save();

            rtFiles.recycle();
            doc.recycle();

            //if we're done: rename it back to the original filename, so it gets cleaned up by the server
            correctedFile.renameTo( iUploadedFile.getServerFile() );
        }


    }
 }