XPages & Angular.js: Fileuploads

When using Angular.js you sooner or later want to upload a file to your Domino server. But to do this, you not only need some nice looking frontend, you also need some code in the backend. For the frontend you can use one of the already exsiting modules which are available for Angular.js, for example the angular-file-upload. For a quick start, I have choosen to modify the provided Simple example.

After stripping down the example files (just saved the whole website with Firefox), you can import all the files into a new database. Mark Roden has written a very good tutorial about the details for this step.

The WebContent folder should look like this:

Now you have to modify the index.html and make all pathes relative:

When you open the index.html in the browser you will see some errors in the console, because of some missing fonts, but we will ignore this issue in this quick example.

Instead, we are adding a link for a download of an uploaded file:

&#160;<a download="{{ item.file.name }}" ng-href="{{ item.file.dlPath }}">download</a></td>

The download link will be filled with the URL of the uploaded attachment in the target database after a successfull upload.

Now it’s time to tell the frontend where to store the file in the backend. For this, you have to modify the controller.js and define the target of the upload process. In this example, the target is a XPage named „upload.xsp„. After uploading a file to the server, the XPage returns the URL of the attachment as a JSON string. To update the link in the frontend, we bind a function to the event „success“ which adds the URL to the current file item:

angular.module('app', ['angularFileUpload'])

.controller('TestController', function ($scope, $fileUploader) {
    'use strict';

    // create a uploader with options
    var uploader = $scope.uploader = $fileUploader.create({
        scope: $scope,   
        url: 'upload.xsp'
    });

    uploader.bind('success', function (event, xhr, item, response) {
        // add the response url to the file item 
        item.file.dlPath = response.url;
    });

});

 [This is the complete controler.js which replaces the file from the module’s example.]

The XPage handles the uploaded files them directly without a file upload control. Every uploaded file will be attached to a single document, and embedded to the Richtext item „Body„. If the upload was successfull, the XPages returns the JSON data containing the URL to the newly created attachment.

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core" rendered="false">
    <xp:this.data>
        <xp:dominoDocument var="documentFile" action="editDocument" concurrencyMode="force" />
    </xp:this.data>

    <xp:this.afterRenderResponse>
        <![CDATA[#{javascript:

            /**
             * saves a uploaded attachment to a datasource
             *
             * @param ds
             *        the datasource
             * @param rtItemName
             *        the richtext item to save the file
             * @return
             *        the name of the uploaded file
             * @author Sven Hasselbach
             */
            function saveAttachment( ds:NotesXspDocument, rtItemName:String ):String {

                // get the file data
                var con = facesContext.getExternalContext();
                var request:com.sun.faces.context.MyHttpServletRequestWrapper = con.getRequest();
                var map:java.util.Map = request.getParameterMap();
                var fileData:com.ibm.xsp.http.UploadedFile = map.get( "file" );

                if( fileData == null )
                      return;

                // get the file
                var tempFile:java.io.File = fileData.getServerFile();
                var correctedFile = new java.io.File( tempFile.getParentFile().getAbsolutePath() +
                java.io.File.separator + fileData.getClientFileName() );
                var success = tempFile.renameTo(correctedFile);

                // create or use an existing RT item
                var rtFiles:NotesRichTextItem = null;
                if(!(ds.getDocument().hasItem( rtItemName ))){
                    rtFiles = ds.getDocument().createRichTextItem( rtItemName )
                }else{
                    rtFiles = ds.getDocument().getFirstItem( rtItemName );
                }

                // embed the file
                rtFiles.embedObject(lotus.domino.local.EmbeddedObject.EMBED_ATTACHMENT, "",
                      correctedFile.getAbsolutePath(), null);

                  // rename the file back for server processing
                  correctedFile.renameTo(tempFile);

                  // save the datasource
                ds.save();

                // return the filenam
                return fileData.getClientFileName();

            }

            // save the doc
            var file = saveAttachment( documentFile, "Body" );

            // create the response
            var res = facesContext.getExternalContext().getResponse();
            res.setContentType( "application/json" );
            res.setCharacterEncoding( "UTF-8" );
            var writer = res.getWriter();

            if( file != null ){
                // send a JSON url string back to the client
                var url = documentFile.getDocument().getHttpURL();
                var fileUrl = url.replace("?OpenDocument","/$File/"+file+"?OpenElement");
                writer.write( '{"url": "' + fileUrl + '"}' );    
            }else{
                // otherwise send empty JSON data
                writer.write( '{}' );
            }
            writer.flush();
            facesContext.responseComplete();
        }]]>
    </xp:this.afterRenderResponse>
</xp:view>

After uploading a file, you can see that the file was uploaded successfully in the firebug console:

When clicking the „download“ link, the file is available to download:

And the attachment was uploaded to the database:

That’s it!

Dieser Beitrag wurde unter Angular.js abgelegt und mit , , , , , , verschlagwortet. Setze ein Lesezeichen auf den Permalink.

2 Antworten zu XPages & Angular.js: Fileuploads

  1. KAKASHI sagt:

    You can give me an example of nsf files?

Schreibe einen Kommentar zu KAKASHI Antworten abbrechen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.