Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rjcorwin/4079218 to your computer and use it in GitHub Desktop.
Save rjcorwin/4079218 to your computer and use it in GitHub Desktop.
With Javascript, create a new file and send it to a CouchDB database as an attachment to a document
// With Javascript, create a new file and send it to a CouchDB database as an attachment of a Document
// Code inspired by "NEW TRICKS IN XMLHTTPREQUEST2" by Eric Bidelman
// http://www.html5rocks.com/en/tutorials/file/xhr2/
/*
* There are two ways of accomplishing this. The first way will always result in a filename of "blob", which is
* bummer. The second way you will be able to name the file what you want. Note that these examples
* assume you have the ID of the database, the ID of the Document, and the most recent revision hash of that Document.
*/
/*
* 1. This version will create the file with file name of "blob"
*/
var formData = new FormData()
formData.append("_attachments", new Blob(['hello world'], {type: 'text/plain'}))
formData.append("_rev", "4-946c660922a86d4bcc19c12272553e42")
var xhr = new XMLHttpRequest()
xhr.open('POST', "/fupload/112", true)
xhr.onload = function(response) {
if(response.status == 200) {
alert("Your file has been uploaded.")
}
}
xhr.send(formData)
/*
* 2. This version will create the file with file name of "hello-world.txt"
*/
var xhr = new XMLHttpRequest()
// Notice we're using PUT, not POST. Also, what we want to name the file is in the URI.
xhr.open('PUT', "/fupload/112/hello-world.txt?rev=15-05bbd9cf2a3c17fff5000d4c1e716099", true)
xhr.onload = function(response) {
if(response.status == 200) {
alert("Your file has been uploaded.")
}
}
xhr.send(new Blob(['hello world'], {type: 'text/plain'}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment