0
点赞
收藏
分享

微信扫一扫

blob对象实现文件的下载和图片预览

余寿 2022-04-14 阅读 58

记录一下在工作中常用的文件下载和图片预览

let str=
       `
       <div>  <p>123<p> </di>
       `
let blob = new Blob([str],{
       type: 'text/html'
})

//* H5新增方法 createObjectURL
btn.onclick = function(){
  this.setAttribute('download','123.html')
  this.href = URL.createObjectURL(blob)
}

//* 文件选择下载
input.onchange = function(e){
	let file = e.target.files[0]
	let a = document.createElement('a')
	a.setAttribute('download','myFile.html')
	a.href = URL.createObjectURL(file)
	a.click()
}

//* 图片预览
input.onchange = function(e){
	let file = e.target.files[0]
	let img = new Image()
	img.src = URL.createObjectURL(file)
	document.body.appendChild(img)
}

//* h5新增异步读取文件
input.onchange = function(e){
	let file = e.target.files[0]
	let fileRead = new FileRead()
	fileRead.onload = function(){
    	img.src = fileRead.result
    }
    fileRead.readAsDataURL(file)  // 关联文件
}
举报

相关推荐

0 条评论