How to upload a blob in Velocity?

There are some options.

  1. Use a HTML form

    In this example we have a form in /upload/form.vm This form needs to use the post method and enctype multipart/form-data. You can only submit files in this way. Other inputs types will not be included in the post parameters. You can use the action url to include parameters. For instance: /upload/form.vm?foo=bar parameter can be asked with $request.get('foo') You can use the multiple attribute on the file input, to upload multiple files at the same time.

    <form method="post" action="/upload/action.vm" enctype="multipart/form-data">
        <input name="file" type="file" multiple> <br>
        <input type="submit">
    </form>
    This will be submitted to /upload/action.vm Here we get all the blobs (files). With a #foreach loop we loop over the blobs and put each one in the field image of a record that has the class image.

    #set($blobs = $request.getBlobs())

    ## Loop over blobs and put each one in a record
    #foreach($blob in $blobs)
        #set($record = $session.newRecord('image')) 
        $record.putVoid('image', $blob)
        #set($void = $record.save())
    #end
  2. Use JavaScript and AJAX

    In this example we have a similar form in  /upload/ajax_form.vm When using JavaScript (and AJAX) the same rules apply. We need the post method and enctype multipart/form-data

    <form id="app_file-upload-form" method="post" action="/upload/ajax_action.vm" enctype="multipart/form-data">
         <input name="file" type="file" multiple> <br>
         <input type="submit">
    </form>


    <script>
         var form = document.getElementById('app_file-upload-form');
         form.addEventListener('submit', function(event) {

             var ajaxURL = form.getAttribute("action");
             var data = new FormData(form);

             // AJAX
             var xhttp = new XMLHttpRequest();
             xhttp.onreadystatechange = function() {
                 if (this.readyState == 4 && this.status == 200) {
                     // Get the output of ajax.am in the console on a successfull request
                    console.log(this.responseText);
                 }
             };

             // XMLHttpRequest - the third parameter indicates this request will be asynchronous (AJAX).
             // You can omit it if you want to do a synchronous request (and land on the URL).
             xhttp.open("POST", ajaxURL, true);
             xhttp.send(data);

             // Prevent form from performing a default submit
            event.preventDefault();
         });
    </script>

    From the file /upload/ajax_action.vm you can return a message on success or failure. In the example above this gets logged in the browser console.