前端处理文件流、base64转文件下载

1. 处理文件流下载

async ipSecDownload() {
  let res = await this.$http.get(
    "/api/UserInfo/Download?type=ExecuteIPsec",
    {
      responseType: "arraybuffer"
    }
  );
  if (res.status !== 200) return this.$message.error(res.statusText);
  this.$message.success(res.statusText);
  
  let blob = new Blob([res.data]);
  let downloadElement = document.createElement("a");
  let href = window.URL.createObjectURL(blob);
  downloadElement.href = href;
  downloadElement.download = "IPSEC逻辑推断日志.txt";
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);
}

2. base64转文件下载

/**
 * base64转Blob函数
 * @param {string} b64Data
 * @param {string} contentType
 * @param {number} sliceSize
 */
b64toBlob(b64Data, contentType, sliceSize) {
  contentType = contentType || "";
  sliceSize = sliceSize || 512;

  var byteCharacters = atob(b64Data);
  var byteArrays = [];

  for (
    var offset = 0;
    offset < byteCharacters.length;
    offset += sliceSize
  ) {
    var slice = byteCharacters.slice(offset, offset + sliceSize);

    var byteNumbers = new Array(slice.length);
    for (var i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    var byteArray = new Uint8Array(byteNumbers);

    byteArrays.push(byteArray);
  }

  var blob = new Blob(byteArrays, { type: contentType });
  return blob;
}

	// 创建隐藏的可下载链接
    var eleLink = document.createElement("a");
    eleLink.download = res.Data.ESSID + ".cap";
    eleLink.style.display = "none";
    // 字符内容转变成blob地址
    var blob = new Blob([this.b64toBlob(res.Data.CapturedDataBase64)]);
    eleLink.href = URL.createObjectURL(blob);
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);

你可能感兴趣的:(JavaScript)