Created
April 29, 2014 07:30
-
-
Save newshorts/11392986 to your computer and use it in GitHub Desktop.
Very Simple File Upload for NodeJS with Express
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
<form class="mediaForm" enctype="multipart/form-data"> | |
<input name="file" type="file" class="media" /> | |
<input type="submit" name="submit" class="submit" /> | |
</form> |
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
(function($) { | |
$(window).load(function() { | |
var files; | |
$('.media').on('change', function(evt) { | |
var file = this.files[0]; | |
console.log(file); | |
}); | |
$('.mediaForm').on('submit', function(evt) { | |
evt.preventDefault(); | |
evt.stopPropagation(); | |
var data = new FormData(); | |
$.each(files, function(key, value) { | |
console.log(key + value); | |
data.append(key, value); | |
}); | |
$.ajax({ | |
url: '/api/photo', | |
type: 'POST', | |
data: data, | |
cache: false, | |
dataType: 'json', | |
processData: false, | |
contentType: false, | |
success: function(data, textStatus, jqXHR) { | |
console.log(data); | |
}, | |
error: function(jqXHR, textStatus, errorThrown) { | |
console.log(errorThrown); | |
} | |
}); | |
}); | |
}); | |
})(jQuery); |
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
// NodeJS server using expressJS | |
app.post('/api/photo', function(request, response) { | |
// take the first file | |
var file = request.files[0]; | |
var errors = new Array(); | |
fs.readFile(file.path, function (err, data) { | |
if(err) throw err; | |
var newPath = __dirname + "/uploads/" + file.name; | |
fs.writeFile(newPath, data, function (err) { | |
if(err) { | |
throw err; | |
errors.push(err); | |
} else { | |
console.log('written'); | |
} | |
}); | |
}); | |
response.json({errors: errors}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment