# 上传下载那些事儿

# 利用表单 Form 进行简单的上传

# 利用 Base64 进行简单的下载

流程

代码实现

function DownloadConfig() {
 let baseUrl = "http://localhost:3000"
 let url = baseUrl + '/download'
  $.ajax({
    type: "post",
    url: 'http://192.168.2.131/api2/platform/download_cfg.json',
    data:'',
    dataType: "",
    async: true,
    cache: false,
    success: function(res) {
      console.log(res.data)
       // 注意axios会多封装一层data
      let bob = dataURLtoBlob(res.data.data)
      console.log(bob)
      let url = URL.createObjectURL(bob)
      downloadFile(url)
    }
  });
}

function dataURLtoBlob(str) {
  //  atob 解码base64
  //  btoa 编码base64
  let bstr = window.atob(str),
  let n = bstr.length,
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr]);
}

function downloadFile(url, name = 'confing_'+Date.now()+'.tar.gz') {
  var a = document.createElement("a")
  a.setAttribute("href", url)
  a.setAttribute("download", name)
  a.setAttribute("target", "_blank")
  let clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
}
import axios from "axios";

export default {
  // 配置/预设导入导出
  configUpload() {
    this.isUploading = true;
    let formData = new FormData();
    formData.append("file", this.file.raw);
    axios
      .post(this.$http.url + "project/import.json", formData, {
        header: {
          "Content-Type": "multipart/form-data"
        }
      })
      .then((res) => {
        this.$message.success("导入成功");
      })
      .catch((e) => {
        this.$message.error("导入失败");
      });
  },
  onUploadChange(file) {
    this.file = file;
    this.fileName = file.name;
  },
  configDownload() {
    this.$refs.form.validate((valid) => {
      if (valid) {
        axios
          .get(this.$url + "project/export.json", {
            responseType: "blob"
          })
          .then((res) => {
            let bob = this.JSONtoBlob(res.data.data);
            const blob = new Blob([res.data], {
              type: headers["content-type"]
            });
            let url = URL.createObjectURL(blob);
            this.downloadFile(url, this.downloadName + ".json");
          });
      }
    });
  },
  JSONtoBlob(data) {
    data = JSON.stringify(data, undefined, 4);
    return new Blob([data], {
      type: "text/json"
    });
  },
  downloadFile(url, name) {
    var a = document.createElement("a");
    a.setAttribute("href", url);
    a.setAttribute("download", name);
    a.setAttribute("target", "_blank");
    let clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
    // 去除a标签
    document.removeChild(a);
    // 释放内存
    URL.revokeObjectURL(url);
    this.handleClose();
  }
};

# 大文件的上传下载

# 文件切分

# 断点续传