美文网首页
单请求断点续传

单请求断点续传

作者: 芸芸众生ing | 来源:发表于2021-04-14 20:52 被阅读0次

    前端代码

    // 单请求断点续传
        async upload_onec(file) {
          const reader = new FileReader();
          reader.onload = (e) => {
            const URL = "http://127.0.0.1:3000/api/upload_onec";
            const buffer = e.currentTarget.result;
            const view = new Uint8Array(buffer);
            const md5 = MD5(view.toString());
            // let params = { md5, filename: file.name };
            fetch(URL + "?md5=" + md5)
              .then((res) => res.json())
              .then(({ data }) => {
                this.uploadFile({ name: file.name, URL, buffer, md5, loaded: data.loaded });
              });
          };
          reader.readAsArrayBuffer(file);
        },
        uploadFile({ name, URL, buffer, md5, loaded }) {
          let xhr = new XMLHttpRequest();
          xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
              const res = JSON.parse(xhr.responseText);
              console.log(res);
            }
          };
          xhr.open("POST", URL + `?filename=${name}&md5=${md5}`, true);
          xhr.setRequestHeader("token", "token");
          xhr.send(buffer.slice(loaded));
        }
    

    后端nodejs代码

    const PATH = require("path");
    const { existsSync, statSync, writeFileSync, appendFileSync, renameSync } = require("fs");
    
    const post = ({ req, config, api }) =>
      new Promise((resolve, reject) => {
        const { md5, filename } = req.query;
        const filepath = PATH.join(config.cacheFilePath, md5);
        const savepath = PATH.join(config.saveFilePath, filename);
        const savefilePath = PATH.join(config.savePath, filename);
        req.on("data", (chunk) => {
          console.log(chunk);
          if (existsSync(filepath)) {
            appendFileSync(filepath, chunk);
          } else {
            writeFileSync(filepath, chunk);
          }
        });
        req.on("end", () => {
          api.ApiMkdir(config.saveFilePath);
          renameSync(filepath, savepath);
          resolve(savefilePath);
        });
        req.on("error", err => {
          console.log("上传错误");
          reject(err)
        });
      });
    const get = ({ req, config }) => {
      const { md5 } = req.query;
      const filepath = PATH.join(config.cacheFilePath, md5);
      if (existsSync(filepath)) {
        return statSync(filepath).size;
      } else {
        return 0;
      }
    }
    
    module.exports = { post, get }

    相关文章

      网友评论

          本文标题:单请求断点续传

          本文链接:https://www.haomeiwen.com/subject/enillltx.html