Skip to content

Instantly share code, notes, and snippets.

@karmi
Created April 3, 2010 07:32
Show Gist options
  • Select an option

  • Save karmi/354230 to your computer and use it in GitHub Desktop.

Select an option

Save karmi/354230 to your computer and use it in GitHub Desktop.
<form id="new_document_form" method="post">
<!-- We need doc _rev in POSTed data for Couch -->
<input type="hidden" name="_rev" value="">
<p><input type="file" name="_attachments"></p>
<p><button type="submit" class="add">Send</button></p>
</form>
// Needs http://malsup.com/jquery/form/ plugin
var upload_attachment = function(form) {
// Store the upload form reference
var form = $(form);
// Obtain new doc ID from Couch
var doc_id = $.couch.newUUID();
// Create new doc in Couch to hold the attachment
var doc = { _id : doc_id,
created_at : new Date() }
db.saveDoc(doc,
{ success : function(response) {
// Update the _rev input with document revision
form.find("input[name='_rev']").val( response.rev );
// Submit the form with file upload via Ajax
form.ajaxSubmit({
url : db.uri + doc_id,
type : 'POST',
dataType : 'json',
// NOTE: ajaxSubmit has only "complete" callback, others are reserved
complete : function(upload_response) {
var result = JSON.parse( $(upload_response.responseText).text() );
if (result.ok) {
$this.message('Document successfully saved.');
$this.display_list( { highlight_last : true } );
} else {
$this.message('Cannot save the document. Reason: ' +
'<code>'+$(upload_response.responseText).text()+'</pre>', 'error');
}
}
});
return false;
},
error : function(status, error, reason) {
alert('Unable to create document in the database ' + db.name +
', reason: ' + reason.toString())
}
});
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment