Last active
August 29, 2015 13:57
-
-
Save trkoch/9568926 to your computer and use it in GitHub Desktop.
Simple file upload from script (e.g. Backbone model) for modern browsers supporting FormData and XMLHttpRequest Level 2
This file contains 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
/* | |
* Update field of a server-side resource expecting a file. | |
* | |
* Backbone's default JSON serialization does not cover file objects. Make sure to trigger this | |
* method after the user has selected a file. | |
* | |
* *srcAttr*: Attribute holding file handle provided by input[type=file], e.g. 'selectedImage' | |
* *targetAttr*: Attribute on server-side expecting a file, e.g. 'image' | |
*/ | |
upload: function (srcAttr, targetAttr) { | |
var file = this.get(srcAttr); | |
if (!file) { | |
return; | |
} | |
if (!file.name) { | |
console.log('Trying to upload an invalid file'); | |
return; | |
} | |
// Build a HTML form in JavaScript. | |
var form = new FormData(); | |
form.append('resource[' + targetAttr + ']', file); | |
// Barebone XHR request with form object as data, | |
// no (intelligent) processing by jquery, simply pass-through. | |
// | |
// Of course, its possible to use native XMLHttpRequest but it | |
// may be missing fields set globally for jQuery (e.g. CSFR token in Rails) | |
return $.ajax({ | |
url: this.url(), | |
data: form, | |
contentType: false, | |
processData: false, | |
type: 'PUT' | |
}).then(function () { | |
// Sync after upload to populate model with uploaded (possibly processed) file | |
return this.save(); | |
}.bind(this)); | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment