学习笔记——node+express+multer实现文件上传

前端文件上传功能编写,已写好样式,想测试一下是否可用。所以自己用node+express+multer来写后端的接口,实现文件上传。


multer包如何使用? 

var express = require('express');
var router = express.Router();
var multer = require('multer')
var fs = require('fs')

// 文件上传后存储的位置
const storeLocation = 'public/uploads/images/'
// 访问已上传文件的位置(自定义)
const visitLocation = 'api/uploads/images/'

// multer包的使用
const uploading = multer({
  dest: storeLocation,
  // 设置上传限制
  // limits: { fileSize: 1000000, files: 5 }
})

const cpUpload = uploading.fields([{ name: 'file', maxCount: 5 }])
router.post('/uploads', cpUpload, (req, res, next) => {
  let files = req.files['file']

  if (files.length === 0) {
    // 上传失败,抛出错误信息
    // res.flag = new Promise((resolve, reject) => {
    //  reject('上传文件为空')
    // })
  } else {
    let urls = []
    for (let i = 0; i < files.length; i++) {
      let file = files[i]
      fs.renameSync(storeLocation + file.filename, storeLocation + file.originalname)
      urls.push({ name: file.originalname, url: visitLocation + file.originalname })
    }

    // 上传成功,返回信息
    // res.flag = new Promise((resolve) => {
    //  resolve(httpResult.success(urls.length === 1 ? urls[0] : urls, '上传成功'))
    // })
  }
  next()
})

你可能感兴趣的:(前端学习,学习,express,前端,node)