URL & webkitURL

本文探讨了在Web开发中使用Base64进行图片预览的方法及其带来的问题,包括浏览器性能影响及如何利用FileReader对象和URL.createObjectURL实现更优的图片加载方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

base64带来的坑

在web中想要是实现图片在线预览的方式有几种
1、先上传
2、使用FileReader对象
3、URL.createObjectURL(file|blob)
base64 能将图片读取成同样大小的base64字符,这样html文件也就随之增大,造成的无非是浏览器卡顿,每一次新的渲染都会很慢

js

var window.URL = window.URL | window.webkitURL;
objectURL = URL.createObjectURL(blob | file);
// objectURL --> blob:http%3A//127.0.0.1%3A8020/32b4467f-5870-44dd-a119-fddf4e6f8f94

提示

1、然而该方法兼容性并不高,只支持chrome 8, firefox4, ie10(fuck),15, safari6
2、官方强调:在每次调用 createObjectURL() 方法时,都会创建一个新的 URL 对象,即使你已经用相同的对象作为参数创建过。
每个对象必须通过调用 URL.revokeObjectURL(objectURL )方法来释放

转载于:https://www.cnblogs.com/iNewbie/p/5710953.html

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue-upload-component Test</title> <script src="https://unpkg.com/vue"></script> <script src="https://unpkg.com/vue-upload-component"></script> </head> <body> <div id="app"> <ul> <li v-for="file in files">{{file.name}} - Error: {{file.error}}, Success: {{file.success}}</li> </ul> <file-upload ref="upload" v-model="files" post-action="/post.method" put-action="/put.method" @input-file="inputFile" @input-filter="inputFilter" > Upload file </file-upload> <button v-show="!$refs.upload || !$refs.upload.active" @click.prevent="$refs.upload.active = true" type="button">Start upload</button> <button v-show="$refs.upload && $refs.upload.active" @click.prevent="$refs.upload.active = false" type="button">Stop upload</button> </div> <script> new Vue({ el: '#app', data: function () { return { files: [] } }, components: { FileUpload: VueUploadComponent }, methods: { /** * Has changed * @param Object|undefined newFile Read only * @param Object|undefined oldFile Read only * @return undefined */ inputFile: function (newFile, oldFile) { if (newFile && oldFile && !newFile.active && oldFile.active) { // Get response data console.log('response', newFile.response) if (newFile.xhr) { // Get the response status code console.log('status', newFile.xhr.status) } } }, /** * Pretreatment * @param Object|undefined newFile Read and write * @param Object|undefined oldFile Read only * @param Function prevent Prevent changing * @return undefined */ inputFilter: function (newFile, oldFile, prevent) { if (newFile && !oldFile) { // Filter non-image file if (!/\.(jpeg|jpe|jpg|gif|png|webp)$/i.test(newFile.name)) { return prevent() } } // Create a blob field newFile.blob = '' let URL = window.URL || window.webkitURL if (URL && URL.createObjectURL) { newFile.blob = URL.createObjectURL(newFile.file) } } } }); </script> </body> </html> 将这个页面改为 vue3 的写法
06-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值