{"size": 1740, "ext": "js", "max_stars_repo_path": "server/routers/file-upload.js", "max_stars_repo_name": "Composur/vue-admin", "max_stars_repo_stars_event_min_datetime": "2020-03-22T10:55:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-22T10:55:27.000Z", "max_issues_repo_path": "server/routers/file-upload.js", "max_issues_repo_name": "Composur/vue-admin", "max_issues_repo_issues_event_min_datetime": "2021-03-10T11:38:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T01:27:08.000Z", "max_forks_repo_path": "server/routers/file-upload.js", "max_forks_repo_name": "Composur/vue-admin", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": 7, "max_forks_count": null, "avg_line_length": 23.2, "max_line_length": 63, "alphanum_fraction": 0.4994252874}
/*
处理文件上传的路由
 */
const multer = require('multer')
const path = require('path')
const fs = require('fs')

const dirPath = path.join(__dirname, '..', 'public/upload')
const storage = multer.diskStorage({
  // destination: 'upload', //string时,服务启动将会自动创建文件夹
  destination: function (req, file, cb) { //函数需手动创建文件夹
    // console.log('destination()', file)
    if (!fs.existsSync(dirPath)) {
      fs.mkdir(dirPath, function (err) {
        if (err) {
          console.log(err)
        } else {
          cb(null, dirPath)
        }
      })
    } else {
      cb(null, dirPath)
    }
  },
  filename: function (req, file, cb) {
    // console.log('filename()', file)
    var ext = path.extname(file.originalname)
    cb(null, file.fieldname + '-' + Date.now() + ext)
  }
})
const upload = multer({storage})
const uploadSingle = upload.single('image')

module.exports = function fileUpload(router) {

  // 上传图片
  router.post('/manage/img/upload', (req, res) => {
    uploadSingle(req, res, function (err) { //错误处理
      if (err) {
        return res.send({
          status: 1,
          msg: '上传文件失败'
        })
      }
      var file = req.file
      res.send({
        status: 0,
        data: {
          name: file.filename,
          url: 'http://localhost:8081/upload/' + file.filename
        }
      })

    })
  })

  // 删除图片
  router.post('/manage/img/delete', (req, res) => {
    const {name} = req.body
    fs.unlink(path.join(dirPath, name), (err) => {
      if (err) {
        console.log(err)
        res.send({
          status: 1,
          msg: '删除文件失败'
        })
      } else {
        res.send({
          status: 0
        })
      }
    })
  })
}
