NodeJS & Express: Upload Images
Blogs20122012-05-24
NodeJS & Express: Upload Images
There is an excellent article showing to use Node.js and Express to upload file/image. For the upload form:
<form id="uploadForm"
enctype="multipart/form-data"
action="/api/photos"
method="post">
<input type="file" id="userPhotoInput" name="userPhoto" />
</form>It uses setInterval call function, that is continually checking the value of the input element, once it has a value it can assume the user has selected a file and it will kick off the upload.
var timerId;
timerId = setInterval(function() {
if($('#userPhotoInput').val() !== '') {
clearInterval(timerId);
$('#uploadForm').submit();
}
}, 500);I can list many reasons that setInterval here is not a suitable solution. For general usage, I change it to onChange event:
$('#userPhotoInput').change(function(e) {
e.preventDefault();
//nothing to do if the upload field is null
if($(this).val()=='' || /^s+$/.test($(this).val()) return false;
else $('#uploadForm').submit();
return false;
});This way seems much better: when upload field changes, the changed file/image immediately uploaded, if null, nothing to upload.
