问题:
我点击了upload.ejs中的提交,我收到错误:“无法发布/上传”
SOLUTION:
我的问题是建筑问题而不是编码问题。
我改变了项目的结构来解决问题。
我创建了一个名为“upload.js”的新文件,用于放入路由器代码。
我还将“upload.ejs”移动到项目的根目录。
我更新了我的“app.js”以考虑新的路由器文件“upload.js”。
我将表单更改为使用“upload.js”。
CODE:
upload.js
{'total_count': '8902',
'total_pages': 179,
'page': 1, # This is what I want to change
'results_per_page': 50,
'data': [
{'id': '7895426',
'team': '123456',
'_subtype': 'Standard Survey',
... },
{'id': '7895427',
'team': '123456',
'_subtype': 'Standard Survey',
... },
...]}
upload.ejs
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;
答案 0 :(得分:1)
您正在向/upload
网址发帖,但您注册的路线是POST /users/upload
。可能你必须将follwing函数移动到routes / index.js文件中:
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());
});
答案 1 :(得分:-1)
您需要使用multer模块:
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);
});