简体   繁体   中英

How to upload a file in Node.js ? Error: Cannot POST /upload

PROBLEM:

I click on submit in my upload.ejs and I get the error: "Cannot POST /upload"


SOLUTION:

My problem was an architectural one more than a coding problem.

I changed the structure of my project to solve the problem.

I created a new file called "upload.js" to put the router code in.

I also moved the "upload.ejs" to the root of the project.

I updated my "app.js" to take into account the new router file "upload.js".

I changed the form to use "upload.js".


CODE:

upload.js

var express = require("express");
var router = express.Router();
var flash = require("connect-flash");

var firebase = require("firebase");

var multer = require("multer");
var upload = multer({dest:"./public/images/uploads/"});

router.get("/", function(req, res, next){
    res.render("upload");
});

router.post("/", upload.single("image"), function(req, res, next){

    if (req.file){
        console.log("Uploading file...");
        var image = req.file.filename;
    }
    else {
        console.log("No file uploaded");
        var image = "noimage.jpg";
    }

    var post = {
        title: req.body.title,
        section: req.body.section,
        image: image,
    }

    var section = req.body.section.toLowerCase();

    firebase.database().ref("posts/"+section).push(post);

    req.flash("success_msg", "Post Created");
    res.redirect("/upload");


});

module.exports = router;

upload.ejs

<form enctype="multipart/form-data" method="post" action="upload">

You are POSTing to /upload url but you the route that you register is POST /users/upload . Possibly you have to move the follwing function into the routes/index.js file:

router.post("/upload", upload.single("image"), function(req, res, next){

    if (req.file){
        console.log("Uploading file...");
        var image = req.file.filename;
    }
    else {
        console.log("No file uploaded");
        var image = "noimage.jpg";
    }

    var post = {
        title: req.body.title,
        section: req.body.section,
        image: image,
    }

    var postRef = fbRef.child("posts");

    postRef.push().set(post);

    req.flash("success_msg", "Post Created")
    res.redirect("/"+ req.body.section.toLowerCase());

});

You need to use multer module:

server.js

multer = require('multer');
app.use(multer({
        dest: './public/uploads/',
        rename: function (fieldname, filename) {
            return filename.replace(/\W+/g, '-').toLowerCase();
        }
}));

upload.js

router.post("/upload",function(req, res, next){
    console.log(req.file);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM