klren0312 / daliy_knowledge

知识积累,正确使用方式是watch
21 stars 4 forks source link

express文件上传 #739

Open klren0312 opened 1 year ago

klren0312 commented 1 year ago
const express = require('express')
const multer = require('multer')
const app = express()
app.use(express.static('upload'))

//设置允许跨域访问该服务.
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'Content-Type')
  res.header('Access-Control-Allow-Methods', '*')
  res.header('Content-Type', 'application/json;charset=utf-8')
  next()
})
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './uploads')
  },
  filename: (req, file, cb) => {
    file.originalname = Date.now() + Buffer.from(file.originalname, 'latin1').toString(
      'utf8'
    )
    cb(null, file.originalname)
  }
})
const upload = multer({ storage })
app.post('/upload', upload.single('file'), (req, res) => {
  res.end(JSON.stringify({
    fileUrl: `http://localhost:4396/static/${req.file.originalname}`  
  }))
})

app.use('/static', express.static('uploads'))

app.listen(4396, () => {
  console.log('listen to 4396')
})