node多文件上传

291 阅读1分钟

1、 使用的依赖

  • multer 文件处理
  • fs 文件依赖
  • express 框架

2、node代码

const express = require('express')//框架
const multer = require('multer')// multer文件处理
const fs = require('fs') 

//设置文件上传路径--我是直接放在根目录下的img文件夹内
const upload = multer({
  dest: './img'
})

/**
 * 上传图片
 */
app.post('/tool/uploadImg',
  async (req, res) => {
    const imgList = req.files//客户端的文件信息列表
    imgList.forEach(imgInfo=>{
      const fileInfo = imgInfo
      const params = {
        name: fileInfo.originalname,
        size: fileInfo.encoding,
        type: fileInfo.mimetype,
        path: fileInfo.path
      }
      //给文件命名
      const newFile = `./img/${params.name}`//新的文件路径
      const oldFile = fileInfo.path //旧的文件路径
      /**
       * 对文件进行改名
       * oldFile, newFile, callback
       */
      fs.rename(oldFile, newFile, async err => {
        if (err) {
          res.json({
            code: 500,
            msg: '失败',
            data: '500'
          })
          return false;
        } else {
          //判断数据库有没有相同的文件,没有再插入
          const imgList = await query(fileSQL.searchAll())
          const findIndex = imgList.findIndex(i=>i.name === fileInfo.originalname)
          if(findIndex===-1){
            //插入
            const rows = await query(fileSQL.insert(params))
          }
        }
      })
    })

    console.log(250, '上传成功')
    res.json({
      code: 200,
      msg: '文件上传成功',
      data: '200'
    })

    //查找数据库内的数据
    //const imgList = await query(fileSQL.search(1000))
  })

3、前端代码

  • 把请求头设置成'Content-Type': 'multipart/form-data'就行。

4、遇到的问题

  • Cannot set headers after they are se nt to the client

说明接口返回了多次,注意node接口的返回

  • 文件上传后,相同的文件会自动覆盖,而数据库不会覆盖相同的数据。

  • 前端显示图片,需要node服务器端再启动一个文件服务器。我们这里用anywhere

anywhere文档