js关于blob与其它对象的转换和下载--草稿







blob --> font--> file download-->动态创建font-family


ws:


ws.onmessage = function(evt){
var dt=new Date().Format("hh:mm:ss");
$("#d").append($("

"+dt+" 接收:"+evt.data+"

"));
var base64Data1= window.URL.createObjectURL(evt.data);
console.log(base64Data1);
var reader = new window.FileReader();
reader.readAsDataURL(evt.data); 
reader.onloadend = function() {
var base64data = reader.result;   
base64data=base64data.replace("data:;", "data:application/font-woff;Content-Disposition: attachment;filename=foobar.png;");
console.log(base64data);
//data:application/font-woff;
window.location.href=base64data;
 } 
}; 





ajax:


var xhr = new XMLHttpRequest();
 
xhr.addEventListener('load', function(){
  if (xhr.status == 200){
  var reader = new window.FileReader();
reader.readAsDataURL(xhr.response); 
reader.onloadend = function() {
var base64data = reader.result;                
console.log(base64data);
$("#st").html("@font-face {font-family: 'lxk2';src : url('"+base64data+"');}");
$("#tx1").attr("font-family",'lxk2')
//window.location.href=base64data.replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png");  ;
 } 
 
  }
});
 
xhr.open('GET', 'http://127.0.0.1:8082/lxksf_simp.woff');
xhr.responseType = 'blob';
xhr.send(null);


});



image --> file download


var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
var imgtmp=can.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition:attachment;filename=1");  
console.log(imgtmp);
saveFile(imgtmp,"wjx.png");
}

img.src="./1.svg";
/**
 * 在本地进行文件保存
 * @param  {String} data     要保存到本地的图片数据
 * @param  {String} filename 文件名
 */
var saveFile = function(data, filename){
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = data;
    save_link.download = filename;
   
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
};



base64 --> blob


注:base64数据为"base64,"后的内容


function 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 blob = b64toBlob(b64Data, contentType);


你可能感兴趣的:(鸡肋)