如何在Node.js中上传文件?错误:无法POST/上载
How to upload a file in Node.js ? Error: Cannot POST /upload
问题:
我在我的upload.ejs中点击提交,我得到错误:"无法POST/上传">
解决方案:
我的问题是架构问题,而不是编码问题。
为了解决这个问题,我改变了项目的结构。
我创建了一个名为"upload.js"的新文件,将路由器代码放入.
我还将"upload.ejs"移到了项目的根目录中。
我更新了我的"app.js",以考虑到新的路由器文件"upload.js"。
我将表单改为使用"upload.js"。
代码:
上传.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;
上传.ejs
<form enctype="multipart/form-data" method="post" action="upload">
您正在POST到/upload
url,但您注册的路由是POST /users/upload
。您可能需要将以下函数移动到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());
});
您需要使用multer模块:
server.js
multer = require('multer');
app.use(multer({
dest: './public/uploads/',
rename: function (fieldname, filename) {
return filename.replace(/'W+/g, '-').toLowerCase();
}
}));
上传.js
router.post("/upload",function(req, res, next){
console.log(req.file);
});
相关文章:
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 未捕获错误:无法在初始化之前调用方法;
- 未捕获的类型错误:无法读取属性'删除'的未定义
- 未捕获的类型错误:无法读取属性'name'即使它存在,也无法定义
- 看到“;未捕获的类型错误:无法读取属性'weight'未定义的“;尽管按照字面上的指示
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- 未捕获的类型错误:无法读取属性'addEventListener'的null chrome扩展名
- 未捕获的语法错误:无法在“文档”上执行“查询选择器”
- 未捕获的类型错误:无法读取属性'状态'在react中为null
- 未捕获的类型错误:无法读取属性'中止'的未定义
- 未捕获的类型错误:无法设置属性'innerHTML'如果为null,则将脚本移动到正文不会;不起作用
- 因果报应-找不到模块:错误:无法解析模块'scs'
- 未捕获的类型错误:无法设置属性'背景'的未定义
- 角度繁忙错误无法加载指定的模板
- Javascript未捕获类型错误:无法读取属性'0'的未定义
- jQuery控制台错误:无法读取属性'top'的未定义
- 未捕获的类型错误: 无法读取未定义的属性“图像”
- 我该如何解决这个问题?“未捕获的类型错误:无法读取 null 的属性'appendChild'”
- JScript 错误: 无法分配给函数结果
- Microsoft JScript运行时错误:无法获取属性'的值;样式':对象为null或未定义