Uploading files to WebApps

Since SiteVision 4.5.4 files uploaded to Web/RESTApps are exposed as sv:temporaryFile-nodes. Here is quick tutorial on how to get started working with uploaded files in a WebApp.

Mission

In this example we aim to upload a file through a WebApp and put in the site's file repository.

The file upload form

We will be using a simple form to upload the file.

<form class="env-form" action="<%= getUrl('/upload') %>" method="post" enctype="multipart/form-data">
   <div class="env-form-element">
      <label for="file" class="env-form-element__label">File</label>
      <div class="env-form-element__control">
         <input id="file" type="file" name="file">
      </div>
   </div>
   <div class="env-form-element">
      <button type="submit" class="env-button env-button--primary">Submit</button>
   </div>
</form>

The WebApp specific getUrl-function returns a URL that will match the /upload route in our WebApp's index.js.

index.js

In index.js we define a route that will accept our request. Since the form is submitted using the POST method we will define a router.post method using the '/upload' path.

(() => {
   const
      router               = require('router'),
      fileUtil             = require('FileUtil'),
      resourceLocatorUtil  = require('ResourceLocatorUtil');

   router.get('/', (req, res) => {
      res.render('/', {});
   });

   router.post('/upload', (req, res) => {
      // Use the req.file method to retrieve the file
      // The method accepts the parameter name of the file to retrieve
      const file = req.file('file');

      // A sv:file will be created and added to the file repository
      fileUtil.createFileFromTemporary(resourceLocatorUtil.getFileRepository(), file);

      res.render('/', {});
   });
})();

Files uploaded to Web/RESTApps are exposed as sv:temporaryFile-nodes. Both FileUtil and ImageUtil in SiteVision's Public API have introduced new methods to facilitate working with this new node type.

As demonstrated, receiving files in a WebApp is a very simple process and the new methods available in FileUtil and ImageUtil provide useful methods to convert uploaded files to actual SiteVision content (sv:file).

Do you want to subscribe to News from SiteVision Developer team? Subscribe here!