3

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

6
  • It seems that you are requesting a route which is not registered in your node server. Can you cross check the URL requested from browser to upload file. Commented Jun 2, 2016 at 4:52
  • 1
    your code is completely fine, i even ran it in my machine. The file is getting uploaded. Except for that you missed the closing tag of <form> Commented Jun 2, 2016 at 5:03
  • @Nivesh i've closed the form on my code missed it here, no the code is not working for me am always getting an error message Commented Jun 2, 2016 at 5:44
  • @JitendraKhatri can yu explain me clearly am a rookie to node development Commented Jun 2, 2016 at 5:46
  • console log the error you are getting from multer Commented Jun 2, 2016 at 6:03

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.