Vue页面png图片的base64格式url转file文件保存后台

convertBase64UrlToBlob(urlData) {
	const bytes = window.atob(urlData.split(',')[1]) // 去掉url的头,并转换为byte

	// 处理异常,将ascii码小于0的转换为大于0
	const ab = new ArrayBuffer(bytes.length)
	const ia = new Uint8Array(ab)
	for ( let i = 0; i < bytes.length; i++) {
		ia[i] = bytes.charCodeAt(i)
	}
	return new Blob([ia], { type: 'image/png'})
}
blobToFile(theBlob, fileName) {
	theBlob.lastModifiedDate = new Date()
	theBlob.name = fileName
	return theBlob
}
SavePng(datauri, fileName, tabId, fieldId) {
	// datauri是base64格式url地址,转换必传
	// fileName是文件名 (xxx.png)
	// tabId和fieldId是我后端需要携带的参数,具体情况视项目而定
	var self = this
	const form = document.forms[0]
	const formData = new FormData(form)
	const blob = self.convertBase64UrlToBlob(datauri)
	const file = self.blobToFile(blob, fileName)
	formData.append('tabId', tabId)
	formData.append('fieldId', fieldId)
	formData.append('file', file)
	
	...... // 发请求将formData保存后台
}

调用 : this.SavePng(url, 'xxx.png', '1', '1') // 后面的两个参数不需要可以不用传

这是我在项目中遇到的需求,将antv/x6的流程图保存后台,点击导出word文件时,后端将图片放到word文件然后导出.
方法是看了别人的文章,不记得是哪篇去了,记录一下用法

Vue 3 中,你可以使用 `FileReader` API 和一些辅助函数来将 Base64 编码的图片数据转换URL,以便显示在页面上。这是一个简单的示例: 首先,你需要安装一个依赖,如果你的项目中还没有安装 `vue-file-loader`,可以通过 npm 或 yarn 来安装: ```bash npm install vue-file-loader @vue/cli-plugin-vuex --save-dev # 或者 yarn add vue-file-loader @vue/cli-plugin-vuex --dev ``` 然后,在你的项目配置文件(如 `vue.config.js`)中配置 base64 图片处理: ```javascript // vue.config.js module.exports = { configureWebpack: { module: { rules: [ { test: /\.(png|jpe?g|gif)$/i, use: ['file-loader'], options: { esModule: false, name: 'static/images/[name].[hash:8].[ext]', }, }, ], }, }, }; ``` 接着,在你的 Vue 组件中,可以这样实现 Base64URL转换: ```html <!-- template.vue --> <template> <div> <img :src="decodeBase64Image(encodedImage)" alt="Decoded Image" /> </div> </template> <script setup> import { ref } from 'vue'; import { createReadStream } from 'fs/promises'; async function decodeBase64Image(base64Image) { const buffer = Buffer.from(atob(base64Image.replace(/^data:image\/\w+;base64,/, '')), 'binary'); const stream = createReadStream({ buffer }); return new Response(stream).blob().then(blob => URL.createObjectURL(blob)); } export default { data() { return { encodedImage: 'data:image/jpeg;base64,base64-encoded-data-goes-here', // 替换为实际的 Base64 数据 }; }, mounted() { this.$watch( () => this.encodedImage, async (newImage) => { if (newImage) { try { this.imageUrl = await decodeBase64Image(newImage); } catch (error) { console.error('Error decoding base64 image:', error); } } }, { deep: true, } ); }, }; </script> ``` 在这个例子中,`decodeBase64Image` 函数会接收 Base64 字符串,将其转换为二进制数据,然后创建一个 ReadableStream,并返回一个包含 URL 的响应。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值