We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
因为涉及到类型转换;responseType 设置为原始的流类型arraybuffer, 不可让浏览器自动转换成 json或者blob; application/octet-stream 转成pdf格式的blob, 需要把文件再转成blob-url;这样浏览器才可以做渲染展示 window.open或者模拟a标签点击都是接受资源定位URL: 常规URL,blobURL 或者 dataURL
function downloadBuffer2Preview(url) { axios.create({ baseURL: '', timeout: 20000, 'responseType': 'arraybuffer', // 只设置responseType就可以, 可以为blob;;注意与content-type区别 }) .get(url) .then(res=> { const dataView = new DataView(res.data); const blobUrl = URL.createObjectURL(new Blob([dataView], {type: 'application/pdf'})); window.open(blobUrl); }) }
注意: new Blob([buffer], {type}) buffer需要用括号括起来, 否则渲染的只是arraybuffer的每位数字的string化字符串
var dataView = new DataView(arrayBuffer); // 便于设置arrayBuffer , 也可直接new Blob([arraybuffer]) var blob = new Blob([dataView], { type: mimeString });
const st = new Blob(['hobop']); st.arrayBuffer().then(j => console.log(j))
new Response(blob).arrayBuffer() .then(/* callback function */); // fetch(URL.createObjectURL(myBlob)).then(res => res.arrayBuffer())
var arrayBuffer; var fileReader = new FileReader(); fileReader.onload = function(event) { arrayBuffer = event.target.result; }; fileReader.readAsArrayBuffer(blob);
见 : https://stackoverflow.com/questions/15341912/how-to-go-from-blob-to-arraybuffer
function dataURL2Blob(dataurl) { const [prefix, data] = dataurl.split(','); const mime = prefix.match(/:(.*?);/)[1], bstr = atob(data), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }
function buffer2Blob(_buffer, type) { return new Blob([_buffer], { type: 'application/octet-stream' }); }
function plain2Blob(text, type) { return new Blob([text], { type: 'text/plain' }); }
var _blob = new Blob([]); //假设它是一个有效的Blob对象 var reader = new FileReader(); reader.onload = (e) => { console.log(reader.result) } /*转为base64:*/ reader.readAsDataURL(_blob); /*转为text: */reader.readAsText(_blob); /*转为arrayBuffer:*/ reader.readAsArrayBuffer(_blob);
The text was updated successfully, but these errors were encountered:
No branches or pull requests
涉及知识点
Q1: 后端返回的下载流,前端做pdf预览
注意: new Blob([buffer], {type}) buffer需要用括号括起来, 否则渲染的只是arraybuffer的每位数字的string化字符串
Q2: buffer和blob互相转换
见 : https://stackoverflow.com/questions/15341912/how-to-go-from-blob-to-arraybuffer
Q3: blob 其他数据类型转换
File 也是 继承自 Blob
The text was updated successfully, but these errors were encountered: