js 文件保存下载

  1. ajax下载文件
    下载文件最简单的是用get方法配合前端的a标签,但是如果是post方法或者是请求需要加头信息就需要用ajax请求下载了,代码如下:
$.get(url, function (data) {

       console.log(typeof(data))
       // 文本文件
       // var blob = new Blob([data],{type:"text/plain;charset=UTF-8"})
       // 文件流
       var blob = new Blob([要保存的文件流], { type: 'application/octet-stream' }),
      // json文件 缩进2
      // var blob = new Blob([JSON.stringify(jsonObj, null, 2)], {type : 'application/json'});
       downloadFile(blob, 'fileName.txt');
   });

function createFile(value, type, name) {
    var blob;
    if (typeof window.Blob == "function") {
      blob = new Blob([value], { type: type });
    } else {
      var BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder;
      var bb = new BlobBuilder();
      bb.append(value);
      blob = bb.getBlob(type);
    }
    blob.name = name;
    return blob;
  }

  function downloadFile(blob, name) {
    if (navigator.msSaveBlob) {
      navigator.msSaveBlob(blob, name);
      return;
    } 
    var WURL = window.URL || window.webkitURL;
    // 转为url:"blob:null/4b27d1aa-d7dc-4c91-a6f8-60f0a1b26134"
    var bloburl = WURL.createObjectURL(blob);
    var anchor = document.createElement("a");
    if ('download' in anchor) {
      anchor.style.visibility = "hidden";
      anchor.href = bloburl;
      anchor.download = name;
      document.body.appendChild(anchor);
      var evt = document.createEvent("MouseEvents");
      evt.initEvent("click", true, true);
      anchor.dispatchEvent(evt);
      document.body.removeChild(anchor);
      //  释放对象
      WURL.revokeObjectURL(bloburl);
    } else {
      location.href = bloburl;
    }
  }
  1. base64 blob bloburl
// base64转字符串
var base64Str = window.atob('str');
// 字符串转base64
var str = window.btoa(base64Str);
/** 
* base64 转 blob 对象 
 */  
function dataURItoBlob(dataURI) {
    // 截取URI的base64字符串 转 string  
    var byteString = atob(dataURI.split(',')[1]);  
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];  
    var ab = new ArrayBuffer(byteString.length);  
    var ia = new Uint8Array(ab);  
    for (var i = 0; i < byteString.length; i++) {  
        ia[i] = byteString.charCodeAt(i);  
    }  
    return new Blob([ia], {type: mimeString});  
}

function fileToBase64(file) {
  if (window.FileReader) { 
    var reader = new FileReader();
    // FileReader 的api 用法
    reader.readAsDataURL (file1);
    // result为带 base64的URi: "data:application/json;base64,ewogICJnb29kIjogImdvb2RieWUiLAogICJoaSI6ICJoZWxsbyIKfQ=="
    return reader.result;
  } else { 
    alert("Not supported by your browser!"); 
  }
  
  return null;
}
  1. FileReader
方法名 参数 描述
abort none 中断读取
readAsBinaryString file 将文件读取为二进制码
readAsDataURL file 将文件读取为 DataURL
readAsText file, [encoding] 将文件读取为文本

你可能感兴趣的:(js 文件保存下载)