Varun Kumar Varun Kumar - 6 months ago 31
Node.js Question

File upload using Multipart fails in nodejs

I'm trying to upload a file in node js using multipart where i get Cannot POST error? I'm totally new to node js so can you help me what i'm doing wrong
My Code
HTML

<form id = "uploadForm"
enctype = "multipart/form-data"
action = "/api/uploadfile"
method = "post">
<input type="file" name="fileUpload"/>
<input type="submit" value="Upload File" name="submit">
</form>


Server.js

var express = require('express');
var app = express();
var multer = require('multer');
app.use(express.static(__dirname));
app.get('/', function(request, response){
response.sendFile("./index.html");
});

var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('fileUpload');


app.post('/api/uploadfile',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});


app.listen(8080);
console.log("App listening on port 8080");


Error message as follows :


Error uploading file

Answer

i tried your code,its working here.The reason may be,

1)you missed out the closing of form tag

<html>
<form id       =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/api/uploadfile"
     method    =  "post"
>
<input type="file" name="fileupload"  /> 
<input type="submit" value="Upload file" name="submit">
</form>
</html>

2)make sure that you have a folder named -> uploads

Comments