美文网首页
multer使用代替formidable

multer使用代替formidable

作者: benbensheng | 来源:发表于2019-03-28 10:38 被阅读0次

https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md
https://www.cnblogs.com/dirkhe/p/7354886.html

var express = require("express");
var app=express();
var multer  = require('multer')
var sd = require('silly-datetime');
var path=require("path");
//设置存储信息
var storage = multer.diskStorage({
    destination: function (req, file, cb) {  //文件夹
      cb(null, './uploads')
    },
    filename: function (req, file, cb) {   //文件名
        var dateTime=sd.format(new Date(), 'YYYYMMDDHHmmss');
        var ran=parseInt(Math.random()*89999+10000);
        var extname=path.extname(file.originalname);
        var newPath="./"+dateTime+ran+extname; 
//以时间+随机数.扩展名 命名
        cb(null, newPath)
    }
  })
//设置中间件upload为file表单的name属性
app.use(multer({ storage: storage }).array("upload"));
app.set("view engine","ejs");
app.get("/",function(req,res){
    res.render("index");
})
app.post("/doPost",function(req,res){
    console.log(req.files);
    console.log(req.body);
    console.log(req.files[0].path);
})
app.listen(3000);

req.files返回
[ { fieldname: 'upload',
    originalname: 'IMG_20180118_071006.jpg',
    encoding: '7bit',
    mimetype: 'image/jpeg',
    destination: './uploads',
    filename: './2019032813213057904.jpg',
    path: 'uploads\\2019032813213057904.jpg',
    size: 4510676 } ]

相关文章

网友评论

      本文标题:multer使用代替formidable

      本文链接:https://www.haomeiwen.com/subject/drgfbqtx.html