nodejs分片上传前后端文件处理

前端代码

<!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>
  <input type="file" id="file">
  <img  alt="加载中" id="src">
  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
  <script>
    var file = document.getElementById('file')
    file.onchange = function (e) {
      var img = document.getElementById('src')
      var base = new FileReader()
      console.log(e.target.files[0])
      var all = e.target.files[0]
      var size = e.target.files[0].size / 10
      var init = 0
      var arr = []
      var index = 0
      while (init < e.target.files[0].size) {
        arr.push(all.slice(init, init + size))
        init = init + size
      }
      console.log(arr)
      arr.map((res, index) => {
        const form = new FormData()
        form.append('file', res)
        axios({
          url: 'http://localhost:4000/upla?name=' + index + '&size=' + 9,
          method: 'post',
          data: form
        }).then(res => {
          console.log(res)
          if (res.data.ok === 200) {
            axios({
              url: 'http://localhost:4000/merge?name=' + e.target.files[0].name,
              method: 'get'
            }).then(suc => {
              console.log(suc)
              img.setAttribute('src',suc.data.url)
            })
          }
        })
      })
      ----------------------------
      // var name = e.target.files[0].name
      // var type = e.target.files[0].type
      // base.readAsDataURL(new Blob([e.target.files[0]]))
      // base.onload = function (e) { 
      //   const base64 = atob(e.target.result.split(',')[1])
      //   const buffer = new ArrayBuffer(base64.length) // 创建缓存视图
      //   const u8 = new Uint8Array(buffer) // 将缓存视图 赋值 字节流数组 来 创建一个模板数组
      //   for(let i =0;i<=base64.length-1;i++) {
      //     u8[i] = base64.charCodeAt(i)
      //   }
      //   // console.log(u8)
      //   // console.log(new Blob([u8],{type: 'image/jpg'}))
-----------------------------------base64转化blob
      //   // const u8 = new Uint8Array(base64.length) // 将缓存视图 赋值 字节流数组 来 创建一个模板数组
      //   // for (let i = base64.length - 1; i >= 0; i--) {
      //   //   u8[i] = base64.charCodeAt(i)
      //   // }

      //   console.log(u8)
      //   const fil = new File([u8], name, { 
      // [Uint8Array]是格式必须
      //     type: type
      //   })
      //   console.log(fil)
----------------------------------base64转化文件对象
      //   const from = new FormData()
      //   from.append('file', fil)
      //   // axios({
      //   //   url: 'http://localhost:4000/upla',
      //   //   method: 'post',
      //   //   data: from
      //   // }).then(res => {
      //   //   console.log(res)
      //   // })
      // }
    }
  </script>
</body>

</html>

后端代码
后端文件目录
nodejs分片上传前后端文件处理_第1张图片

var express = require('express')
var crypto = require('./crypto')
var app = express()
var path = require('path')
var fs = require('fs')
var multiparty = require('multiparty')
app.use('/css', express.static('./public/css'))
app.use('/js', express.static('./public/js'))
app.use('/img', express.static('./public/img'))
app.use('/fonts', express.static('./public/fonts'))
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "token,name,age,Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.header('X-Powered-By', '123')
  res.header('Access-Control-Expose-Headers', 'setcookie,X-Powered-By')
  next();
});
app.use('/upla', (req, res) => { // 接收文件上传
  let form = new multiparty.Form({
    uploadDir: './public/merge' //指定上传的文件路径
  });
  let imgName = req.query.name
  let size = req.query.size
  form.parse(req, (err, field, files) => {
    files && files.file.map(x => { // 必须这样写
      let img = imgName || x.originalFilename
      fs.rename(x.path, './public/merge/' + img, () => {
        if (size === imgName) {
          res.json({ok:200}) // 判断分片全部完成
        } else {
          res.end(JSON.stringify({
            ok: 304
          }))
        }
      })
    })
  })
  form.on('field', (name, value) => {
    // name:字段名
    // value:值
    console.log('数据:', name, value);

  })
  //接收文件数据
  form.on('file', (name, file) => {
    console.log('文件:', name, file);
  })
  //表单解析完成
  form.on('close', () => {
    console.log('完成');
  })
})
app.get('/merge', (req, res) => { 
// 触发上个分片接口成功回调发送请求
  let filePath = './public/img/' + req.query.name
  fs.readdir('./public/merge', (err, list) => {
    console.log(list)
    list.map(res => {
      fs.appendFileSync(filePath, fs.readFileSync('./public/merge/' + res)); // 读取返回结果 然后追加路径
      fs.unlinkSync('./public/merge/' + res) // 删除分片
    })
    res.json({
      url: `http://localhost:4000/img/${req.query.name}`
    })
  })
})


app.use('/demo', (req, res) => {
  res.json({
    ok: 200
  })
})



app.listen(4000, () => {
  console.log('服务开启')
})

你可能感兴趣的:(笔记,nodejs)