目前我有这个:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
router.post('/registo',upload.single('file'), function (req, res) {
但是传递的文件的文件扩展名没有保存,并且multer给它一个随机名称,所以我看到这样的东西来纠正这个问题:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype));
});
}
});
var upload = multer({ storage: storage });
router.post('/registo',upload, function (req, res) {
但是我得到了一个错误:连接被拒绝,我不知道为什么会发生这种情况
答案 0 :(得分:0)
我如何使用multer上传文件。 节点代码
var multer = require('multer');
var fs = require('fs');
var Grid = require('gridfs-stream');
var router = express.Router();
var upload = multer({dest: 'uploads/'});
mongoose.createConnection('mongodb://127.0.0.1/obi');
router.post('/upload', upload.any(), function (req, res) {
var conn = mongoose.connection;
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var path = req.files[0].path
var path_name = req.files[0].originalname
var gfs = Grid(conn.db);
var writestream = gfs.createWriteStream({
filename: path_name
});
fs.createReadStream(path).pipe(writestream);
writestream.on('close', function (file) {
res.json(file.filename + 'Written To DB');
fs.unlink(req.files[0].path, function () {
res.json({id: file._id, message: "success"});
});
});
})
希望这适合你。