h5 blob的简单使用
blob 创建方式
- 字符串
let myBlobParts = ['<html><h2>Hello Leo</h2></html>']; // 一个包含DOMString的数组
let myBlob = new Blob(myBlobParts, {type : 'text/html', endings: "transparent"}); // 得到 blob
console.log(myBlob.size + " bytes size");
// Output: 31 bytes size
console.log(myBlob.type + " is the type");
// Output: text/html is the type
- 二进制数组
let hello = new Uint8Array([72, 101, 108, 108, 111]); // 二进制格式的 "hello"
let blob = new Blob([hello, ' ', 'leo'], {type: 'text/plain'});
// Output: "Hello leo"
- 分隔
let blob1 = new Blob(['<html><h2>Hello Leo</h2></html>'], {type : 'text/html', endings: "transparent"});
let blob2 = new Blob(['<html><h2>Happy Boy!</h2></html>'], {type : 'text/html', endings: "transparent"});
let slice1 = blob1.slice(16);
let slice2 = blob2.slice(0, 16); await slice1.text();
// currtent slice1 value: "Leo</h2></html>"
await slice2.text();
// currtent slice2 value: "<html><h2>Happy "
let newBlob = new Blob([slice2, slice1], {type : 'text/html', endings: "transparent"});
await newBlob.text();
// currtent newBlob value: "<html><h2>Happy Leo</h2></html>"
实际场景
- 图片预览 data url / blob url /obj url
<body>
<h1>1.DataURL方式:</h1>
<input type="file" accept="image/*" onchange="selectFileForDataURL(event)">
<img id="output1">
<h1>2.Blob方式:</h1>
<input type="file" accept="image/*" onchange="selectFileForBlob(event)">
<img id="output2">
<script>
// 1.DataURL方式:
async function selectFileForDataURL () {
const reader = new FileReader()
reader.onload = function () {
const output = document.querySelector('#output1')
output.src = reader.result
}
reader.readAsDataURL(event.target.files[0])
}
//2.Blob方式:
async function selectFileForBlob () {
const reader = new FileReader()
const output = document.querySelector('#output2')
const imgUrl = window.URL.createObjectURL(event.target.files[0])
output.src = imgUrl
reader.onload = function (event) { window.URL.revokeObjectURL(imgUrl) }
} </script>
</body>
图片预览 分片上传
<body>
<input type="file" accept="image/*" onchange="selectFile(event)">
<button onclick="upload()">上传</button>
<img id="output">
<script> const chunkSize = 10000
const url = 'https://httpbin.org/post'
async function selectFile () {
// 本地预览
const reader = new FileReader()
reader.onload = function () {
const output = document.querySelector('#output')
output.src = reader.result
}
reader.readAsDataURL(event.target.files[0])
// 分片上传
await upload(event.target.files[0])
}
async function upload (files) {
const file = files
for (let start = 0; start < file.size; start += chunkSize) {
const chunk = file.slice(start, start + chunkSize + 1)
const fd = new FormData()
fd.append('data', chunk)
await fetch(url, { method: 'post', body: fd }).then((res) => {
console.log(res)
res.text()
})
}
} </script>
</body>
图片预览 断点续传
<body><input type="file" accept="image/*" onchange="selectFile(event)">
<button onclick="upload()">上传</button>
<button onclick="pause()">暂停</button>
<button onclick="continues()">继续</button>
<img id="output" src="" alt="">
<script> const chunkSize = 30000
let start = 0, curFile, isPause = false
const url = 'https://httpbin.org/post'
async function selectFile () {
const reader = new FileReader()
reader.onload = function () {
const output = document.querySelector('#output')
output.src = reader.result
}
reader.readAsDataURL(event.target.files[0])
curFile = event.target.files[0]
}
async function upload () {
const file = curFile
for (start; start < file.size; start += chunkSize) {
if (isPause) return
const chunk = file.slice(start, start + chunkSize + 1)
const fd = new FormData()
fd.append('data', chunk)
await fetch(url, { method: 'post', body: fd }).then((res) => { res.text() })
if (chunk.size < chunkSize) {
uploadSuccess()
return
}
}
}
function pause () { isPause = true }
function continues () {
isPause = false
upload()
}
function uploadSuccess () {
isPause = false
start = 0
} </script>
</body>
js 下载数据
<body>
<button onClick="download1()">使用 XMLHttpRequest 下载</button>
<button onClick="download2()">使用 fetch 下载</button>
<img id="pingan">
<script> const url = 'http://images.pingan8787.com/TinyCompiler/111.png'
const pingan = document.querySelector('#pingan')
function download1 () {
const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'blob'
xhr.onload = () => { renderImage(xhr.response) }
xhr.send(null)
}
function download2 () {
fetch(url).then(res => { return res.blob() }).then(myBlob => { renderImage(myBlob) })
}
function renderImage (data) {
let objectURL = URL.createObjectURL(data)
pingan.src = objectURL
// 根据业务需要手动调用
URL.revokeObjectURL(imgUrl)
}
</script>
</body>
下载文件
<body>
<button onclick="download()">Blob 文件下载</button>
<script> function download () {
const fileName = 'Blob文件.txt'
const myBlob = new Blob(['一文彻底掌握 Blob Web API'], { type: 'text/plain' })
downloadFun(fileName, myBlob)
}
function downloadFun (fileName, blob) {
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = fileName
link.click()
link.remove()
URL.revokeObjectURL(link.href)
} </script>
</body>
图片压缩
<body><input type="file" accept="image/*" onchange="loadFile(event)"/>
<script>
// compress.js
const MAX_WIDTH = 800
// 图片最大宽度
// 图片压缩方法
function compress (base64, quality, mimeType) {
let canvas = document.createElement('canvas')
let img = document.createElement('img')
img.crossOrigin = 'anonymous'
return new Promise((resolve, reject) => {
img.src = base64
img.onload = () => {
let targetWidth, targetHeight
if (img.width > MAX_WIDTH) {
targetWidth = MAX_WIDTH
targetHeight = (img.height * MAX_WIDTH) / img.width
} else {
targetWidth = img.width
targetHeight = img.height
}
canvas.width = targetWidth
canvas.height = targetHeight
let ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, targetWidth, targetHeight)
// 清除画布
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
let imageData = canvas.toDataURL(mimeType, quality / 100)
// 设置图片质量
resolve(imageData)
}
})
}
// 为了进一步减少传输的数据量,我们可以把它转换为 Blob 对象
function dataUrlToBlob (base64, mimeType) {
let bytes = window.atob(base64.split(',')[1])
let ab = new ArrayBuffer(bytes.length)
let ia = new Uint8Array(ab)
for (let i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i) }
return new Blob([ab], { type: mimeType })
}
// 通过 AJAX 提交到服务器
function uploadFile (url, blob) {
let formData = new FormData()
let request = new XMLHttpRequest()
formData.append('image', blob)
request.open('POST', url, true)
request.send(formData)
}
function loadFile (event) {
const reader = new FileReader()
reader.onload = async function () {
let compressedDataURL = await compress(reader.result, 90, 'image/jpeg')
let compressedImageBlob = dataUrlToBlob(compressedDataURL)
uploadFile('https://httpbin.org/post', compressedImageBlob)
}
reader.readAsDataURL(event.target.files[0])
} </script>
</body>
生成pdf
<body><h3>客户端生成 PDF 示例</h3>
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
<script> (function generatePdf () {
const doc = new jsPDF()
doc.text('Hello semlinker!', 66, 88)
const blob = new Blob([doc.output()], { type: 'application/pdf' })
blob.text().then((blobAsText) => { console.log(blobAsText) })
})()
// 带图片的
let imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/...'
let doc = new jsPDF(); doc.setFontSize(40); d
oc.text(35, 25, 'Paranyan loves jsPDF');
doc.addImage(imgData, 'JPEG', 15, 40, 180, 160)
</script>
</body>
blob to arraybuffer
const buffer = new ArrayBuffer(16);
const blob = new Blob([buffer]);
#### blob to arraybuffer
const blob = new Blob([1,2,3,4,5]);
const reader = new FileReader();
reader.onload = function() {
console.log(this.result);
}
reader.readAsArrayBuffer(blob);
#### ajax接受 blob arraybuffer
function GET(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer'; // or xhr.responseType = "blob";
xhr.send();
xhr.onload = function(e) {
if (xhr.status != 200) {
alert("Unexpected status code " + xhr.status + " for " + url);
return false;
}
callback(new Uint8Array(xhr.response)); // or new Blob([xhr.response]); }; }
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/16315218.html