html文件上传保存-(.html and string translate into .html )

//上传h5编辑器编辑的html内容
uploadHtml(newsId?: any) {
const news = newsId !== undefined ? newsId : 'new';
let uploadFile = this.dataURLtoBlob(`data:text/html;base64,${new Buffer(this.newsInfo.content).toString('base64')}`) ;
let form = new FormData();
form.append(`news_${news}.html`, uploadFile , `news_${news}.html`);
return this.smartrecService.uploadFile(form, 'html');
}

//将h5编辑器编辑好的html内容组装成blob对象
dataURLtoBlob(dataurl: string) {
const arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}

//通过contentId获取h5编辑器编辑的html内容,并转化为字符串
getHtml(contentId: any): void {
const url = this.smartrecService.getContentUrlById(contentId);
let xhr = new XMLHttpRequest();
   xhr.open('GET', url);
xhr.responseType = "arraybuffer";
xhr.send();
xhr.onreadystatechange = function() {
    if ( xhr.readyState == 4 && xhr.status == 200 ) {
const htmlBuffer = new Buffer(new Uint8Array(xhr.response));
const htmlStr = htmlBuffer.toString();
try {
JSON.parse(htmlStr);
} catch(e) {
this.newsInfo.content = htmlStr;
}
    }
    }.bind(this);
}
原文地址:https://www.cnblogs.com/lyue1404/p/8677665.html