Created
November 15, 2012 15:35
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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