Search code examples
htmlxquerymarklogic

How to use XQuery and HTML to upload files to MarkLogic?


As my question states I am trying to use XQuery and a simple HTML form to upload files to my MarkLogic local database. I already connected to a HTTP-server.

My code now looks like this:

Form:

<div id="content">
    <form name="test" action="upload.xqy?uid={xdmp:random()}" method="post"
          enctype="multipart/form-data">
    <p><label>File to upload:
    <input type="file" class="name" name="upload" size="50"/></label></p>
    <p><input type="submit" value="Upload and Get Results"/></p>
    </form>
  </div>

upload.xqy:

 let $filename := xdmp:get-request-field-filename("upload")
 let $collection := "semansysdocs"
 let $fileLocation := xdmp:get-request-path()
 return
xdmp:document-load($fileLocation,
  map:map() => map:with("uri", $filename)
            => map:with("permissions", xdmp:default-permissions())
            => map:with("collections", $collection)
)

The docs simply state to use xdmp:document-insert(), but I do not understand where.

Is there a way to specify where the file is coming from to get the $fileLocation, or do i need an other method to do this?

Thank you!


Solution

  • Your form is already sending both filename and file data. xdmp:get-request-field-filename('upload') returns the original file path as sent by the browser, and xdmp:get-request-field('upload') will get you the data. I think you are looking for something like:

    let $filename := xdmp:get-request-field-filename("upload")
    let $file := xdmp:get-request-field("upload")
    let $collection := "semansysdocs"
    return
      xdmp:document-insert(
        $filename,
        $file,
        xdmp:default-permissions(),
        (xdmp:default-collections(), $collection)
      )
    

    HTH!