I'm trying to show an image on index.html after uploading it using node.js, express and multer. The multer implementation is based on a tutorial.
- The upload works. The image shows up in "/uploads" and the console.log is done as expected.
- The index.html shows "File uploaded." from the message var.
- Dev tools console says: GET http://127.0.0.1:3000/uploads/test1423920987055.jpg 404 (Not Found).
- I've tried to get the picture directly via < img > but it doesn't show.
I would be really grateful if I could get an explanation so that I understand what I'm missing.
Here's my server.js:
app.use(express.static(__dirname + '/uploads'));
app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
message = "<p>File uploaded.</p>"
message += "<p><img src=\"" + file.path + "\"> </p>";
done=true;
}
}));
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.post('/api/photo',function(req,res){
if(done==true){
console.log(req.files);
res.end(message);
//res.end("File uploaded.");
}
});
app.listen(3000,function(){
console.log("Working on port 3000");
});
and my index.html:
<html>
<head>
<title>File upload Node.</title>
</head>
<body>
<form id="uploadForm"
enctype="multipart/form-data"
action="/api/photo"
method="post">
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
</form>
<div class="pic"> </div>
<img src="http://127.0.0.1:3000/uploads/test1423920256762.jpg">
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script>
$(document).ready(function() {
$('#uploadForm').submit(function() {
$(this).ajaxSubmit({
error: function(xhr) {
status('Error: ' + xhr.status);
},
success: function(response) {
$(response).appendTo('.pic');
console.log(response);
}
});
return false;
});
});
</script>
</html>
Thank you for every hint in advance.