美文网首页
express 文件上传下载

express 文件上传下载

作者: l4u | 来源:发表于2018-08-25 16:55 被阅读0次

安装包并引入:

var multer = require('multer')

const uuidV1 = require('uuid/v1')

通过 filename 属性定制

var storage = multer.diskStorage({

  destination: function (req, file, cb) {

    cb(null, 'upload/') // 保存的路径,备注:需要自己创建

  },

  filename: function (req, file, cb) {

    // 将保存文件名设置为 字段名 + 时间戳

    let fileFormat = (file.originalname).split('.') // 取后缀

    cb(null, uuidV1() + '.' + fileFormat[fileFormat.length - 1])

  }

})

/通过 storage 选项来对 上传行为 进行定制化

var upload = multer({ storage: storage })

// 单图上传

router.post('/upload', upload.single('file'), function(req, res, next) {

jsonWrite(res, {file: req.file.filename})

})

// 图片下载

router.get('/download', function(req, res, next) {

let filename = req.query.file

res.download('./upload/' + filename)

})

相关文章

网友评论

      本文标题:express 文件上传下载

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