我在基于Node.js / MongoDB的网站上工作,我试图使用Express,Jade和Multer直接在服务器上上传图像,但无论我做什么,我都可以&#39 ; t achive上传文件扩展名。
我的app.js文件中有这个:
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
var upload = multer({ storage: storage });
var app = express();
mongoose.connect("mongodb://localhost/primera_pagina");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(multer({dest: "./uploads"}).single("image_avatar"));
var productSchema = {
title:String,
description:String,
imageURL:String,
pricing:Number
};
var Product = mongoose.model("Product", productSchema);
app.set("view engine","jade");
app.use(express.static("public"));
app.get("/",function(req,res){
res.render("index");
});
app.post("/productos",function(req,res){
if(req.body.password == "123"){
var data = {
title: req.body.title,
description: req.body.description,
imageURL: "image_avatar",
pricing: req.body.pricing
}
var product = new Product(data);
console.log(req.file)
}else{
res.render("index");
}
});
app.get("/productos/new",function(req,res){
res.render("productos/new");
});
app.listen(8080);
有什么想法吗?我在互联网上搜索并尝试使用multer添加文件扩展名的每一种方法,但没有一种方法有效。
答案 0 :(得分:0)
由于安全性和冲突原因,Multer剥离了文件扩展名。要解决此问题,请尝试以下方法:
var path = require('path')
var multer = require('multer')
var mime = require('mime-types')
var storage = multer.diskStorage({
destination: './uploads/',
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
if (err) return cb(err)
cb(null, raw.toString('hex') + mime.extension(file.mimetype))
})
}
})
var upload = multer({ storage: storage })
(来自https://github.com/expressjs/multer/issues/170#issuecomment-123402678)
它会分配一个随机文件名,但保持文件扩展名。
您还应该在multer中使用authorize字段,因为当用户拥有正确的密码时,您似乎只需要文件。做这样的事情:
var upload = multer({ storage: storage }, limits : { fileFilter: authorize });
function authorize(req, file, cb) {
if (req.body.password == PASS) {
cb(null, true); //accept
} else {
cb(null, false); //reject
}
}
如果用户输入了正确的密码,这只会将文件保存到磁盘。