express-上传文件

话不多说 直接看代码

var fs=require('fs')

var multer  = require('multer')

var createFolder=function(folder){ //创建文件夹的方法
  try{
    fs.accessSync(folder)
  }catch(e){
    fs.mkdirSync(folder)
  }
}
var uploadFolder='./upload/'
createFolder(uploadFolder)

var storage = multer.diskStorage({
  destination: function (req, file, cb) {//存放的文件夹
    cb(null, uploadFolder) 
  },
  filename: function (req, file, cb) {
    console.log(file.originalname,'cc')
    cb(null, file.fieldname + '-' + Date.now()) //存放的名字
  }
})
var upload = multer({ storage:storage })

//上传文件的接口
app.post('/upload',upload.single('logo'),function(req,res){
  console.log(req.file) //原文件的名字 originalname
  res.send({'ret_coder':0})
})

 

上传画面

form.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <h2>单图上传</h2>
    <input type="file" name="logo">
    <input type="submit" value="提交">
  </form>
</body>
</html>

进入上传画面的接口

//文件上传页面
app.get('/form',function(req,res){
  // var form=fs.readFileSync('./form.html',{encoding:"utf8"})
  // res.send(form)
  res.sendFile(__dirname + '/form.html')
})

 

posted on 2020-11-27 11:05  秃了头也不退休  阅读(170)  评论(0编辑  收藏  举报

导航