流年*https://i.cnblogs.com/files

关于ajax 异步文件上传 node 文件后台接口

<body>
  <img src="" alt="" id="img">
    <input type="file" name="myfile" size="50" id="file">


  <script src='https://cdn.bootcss.com/axios/0.16.1/axios.min.js'></script>
//使用的axios库发起http请求
  <script src='https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js'></script>

  <script>
    $("#file").change(function () { 
var file = $(this)[0].files[0]
//拿到上传文件的信息
//使用FormDate接口进行上传文件
      var data = new FormData()
      //  console.log(file);
      data.append("myfile", file)
      axios.post('/files', data, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
       // console.log(res.data.data)
       $("#img").attr("src",res.data.data.url)
      })
    })
  </script>
</body>


//后台文件接口代码 ,这里使用node 作为后台语言,使用node 强大的express框架。
const express=require('express')
//使用node 第三方包multer 进行文件上传
const multer=require('multer')
//对上传文件body里的内容进行解析
var bodyParser = require('body-parser');
const PORT=4520
const app=express()

//express.static  web 静态服务器指定上传的文件
所放的目录,此处上传文件放在  imgs 文件夹下。
app.use('/files',express.static('imgs'))
app.use(bodyParser.urlencoded({ extended: false }));
  //使用multer进行指定上传文件所放的目录。
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, path.join(__dirname,"imgs"))
    },
 //对上传文件进行命名
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now() + '.' +'jpg')
    }
  })
  //使用multer进行文件上传
  var file = multer({ storage: storage })
app.get('/',(req,res)=>{
 res.sendFile(path.join(__dirname,'flie.html'))
})
app.post('/files',file.single('myfile'),(req,res)=>{
//上传图片的访问路径
   const url=(`http://127.0.0.1:4520/files/${req.file.filename}`);   
    res.send({
      status:200,
      msg:"sucessful",
      data:{
        url
      }
    })
})
app.listen(PORT,()=>{
    console.log(`服务器运行在${PORT}`);
})

posted on 2021-01-04 10:03  流年*  阅读(53)  评论(0编辑  收藏  举报

导航