Jump to content

XQuery/Uploading Files

From Wikibooks, open books for an open world

Motivation

[edit | edit source]

You want to upload files to your eXist database using simple HTML forms.

Method

[edit | edit source]

We will use the HTML <input> element in the web form and the store function in an XQuery.

HTML Form

[edit | edit source]

We will use a standard HTML form but we will add a enctype="multipart/form-data" attribute.

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>HTML Upload</title>
    </head>
    <body>
        <form enctype="multipart/form-data" method="post" action="upload.xq">
            <fieldset>
                <legend>Upload Document:</legend>
                <input type="file" name="file"/>
                <input type="submit" value="Upload"/>
            </fieldset>
        </form>
    </body>
</html>

Screen Image:

XQuery

[edit | edit source]

On the server side, we will use the request:get-uploaded-file-name() to get the name of the incoming file and the request:get-uploaded-file-data() function to get the data from the file. We can then used the xmldb:store() function to save the file.

File: upload.xq

let $collection := '/db/test/upload-test'
let $filename := request:get-uploaded-file-name('file')

(: make sure you use the right user permissions that has write access to this collection :)
let $login := xmldb:login($collection, 'admin', 'my-admin-password')
let $store := xmldb:store($collection, $filename, request:get-uploaded-file-data('file'))

return
<results>
   <message>File {$filename} has been stored at collection={$collection}.</message>
</results>

Acknowledgments

[edit | edit source]

This example was posted on the eXist open mailing list by RĂ©mi Arnaud on Nov. 05, 2010.