I don’t get attachment upload for the browser to work.
Some hints are here, others there. The docs are quite good but I’m unable to translate that to a AJAX upload.
I’m looking for a super simple HTML/JavaScript example (with or w/o jQuery) of how to upload a file from (relatively modern) browser to the db without making use of jquery.couch.app.js wrapper or stuff. The simpler the besser.
Any help appreciated.
Alright, here’s your pure JavaScript file upload implementation.
The basic algorithm is like this:
The HTML part basically consists of a simple form with two elements, an input of type
fileand a button of typesubmit.Now to the JavaScript part.
Basically, I intercept the
submitevent of the form by binding my own function to the form’sonsubmitevent and returning false.In that event handler I call my main function with two parameters. The first one being the document name and the second one being the file to upload.
In my
uploadFile()function I set the file name, file type and grab some instances. The first HTTP request is a GET request to obtain the current revision of the document. If that request succeeds I prepare the PUT request (the actual upload request) by setting the previously obtained revision, the proper content type and then I convert the file to an ArrayBuffer. Once that’s done I just send the HTTP request I’ve just prepared and then I relax.The standalone attachment upload scheme looks like this:
Of course using the proper content type in the HTTP request header.
Note: I’m well aware that I’m not making use of defensive programming here at all, I did that deliberately for brevity.