Created
August 13, 2013 22:44
-
-
Save dylants/6226430 to your computer and use it in GitHub Desktop.
Upload an image from a Backbone/jQuery client side app to a Node server
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
/* | |
* CLIENT SIDE CODE | |
*/ | |
// perform a file upload | |
file = this.$("input[name='image-file']").prop("files")[0]; | |
formData = new FormData(); | |
formData.append("image", file); | |
$.ajax({ | |
type: "POST", | |
url: "/upload/photo", | |
data: formData, | |
// tells jQuery to not process the form data since it's a file | |
processData: false, | |
cache: false, | |
// tells jQuery to not include a content type, to avoid errors | |
contentType: false | |
}).done(function(response) { | |
// process response... | |
}).fail(function(jqXHR, textStatus, errorThrown) { | |
// process failure | |
}); | |
/* | |
* SERVER SIDE CODE | |
*/ | |
// Make sure to include bodyParser in Node's app config: | |
// app.use(express.bodyParser()); | |
var fs = require("fs"); | |
module.exports = function(app) { | |
app.post("/upload/photo", function(req, res) { | |
// access the photo via: | |
// req.files.photo | |
console.log(req.files.photo.path); | |
// create a stream to upload from here (if need be) | |
console.log(fs.createReadStream(req.files.photo.path)); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment