javascript - VueJs 在数组中渲染图像对象
问题描述
我想在渲染之前将图像对象转换为 base64 数据 url。图像对象在一个数组中,我首先存储它,如下所示
handleFileChange(e, index) {
let file = e.target.files[0]
console.log(file)
let myFilesLength = this.form.files.length
myFilesLength += 1
if (myFilesLength == index) {
this.form.files.push(file)
} else {
let html = '<div class="modal-cont"><h4>Please insert image in sequence.'+
'</h4><div class="alert__icon"><span></span></div></div>'
Swal.fire({
customClass: {
popup: 'error-modal',
},
html: html,
showCloseButton: true,
allowOutsideClick: false,
})
}
e.preventDefault()
},
然后我在我的 html 中使用这个数组来显示我存储的图像
<div class="tabs--custom__select">
<div class="number__select-box" v-for="index in [0, 1 ,2 ,3 ,4 ,5 ,6 ,7]" :key="index">
<div class="number__select-inr">
<a href="javascript:void(0);" class="custom-images">
<h2 v-if="index < form.files.length">
<img @click="addAnswer(form.files[index])" :src="convertBase64(form.files[index])">
</h2>
<h2 v-else>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
</h2>
</a>
</div>
</div>
</div>
正如您在 img 元素 src 属性上看到的那样,我调用另一个函数将图像对象转换为 base64 数据 url 我在下面显示了函数代码
convertBase64(file) {
const dataUrl = new Promise ((resolve, reject) => {
var reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
})
dataUrl.then(url => {
return url
}).catch(error => {
console.log('error '+ error)
})
},
但是当我测试我的代码时,它会呈现空图像
解决方案
您可以使用URL.createObjectURL(files[0])
生成网址。
codepen - https://codepen.io/anon/pen/XGYoyr
推荐阅读
- java - 如何使用带有 Selenium 和 Java 的 XPath 提取表中迭代特定行的文本
- javascript - PWA 应用程序中的文件可以缓存多长时间以及可以缓存的文件的最大大小?
- c# - 当我将 ForeignKey 添加到另一个 DbContext 时,Ef 正在创建新表
- android - 如何在上传到 Firebase 之前压缩图像?
- amazon-web-services - 具有 Amplify 和 Cognito 的自定义 OpenID 提供程序
- javascript - 我如何在 reactJS 中调整大小以使其适合屏幕?
- python - Python中的文本文件到JSON数据
- audio - 2 个 wav 文件的 GStreamer 管道到具有 2 个通道的单个 RTSP
- mongodb - 如何在 MongoDB 中查找具有以给定字符串开头的字段值的所有文档?
- lotus-domino - 按年份和将增加 +1 的数字创建序列号