uni-app 富文本标题rich-text不能渲染img标签src是本地文件地址的图片
uni-app 富文本标题rich-text不能渲染img标签src是本地文件地址的图片
| 开发环境 | 版本号 | 项目创建方式 |
|---|---|---|
| Windows | Windows 功能体验包 1000.26100.84.0 | HBuilderX |
示例代码:
<template> <view> <text class="title">{{title}}</text> <image class="image-dom" :src="networkPreviewUrl" mode="aspectFill"></image> <button type="default" [@click](/user/click)="downloadImage">下载</button> <image class="image-dom" :src="temporaryPreviewUrl" mode="aspectFill"></image> <button type="default" [@click](/user/click)="saveImage">保存</button> <image class="image-dom" :src="previewUrl" mode="aspectFill"></image> {{nodesStr}} <rich-text :nodes="nodesStr" mode="web"></rich-text> </view> </template> ```<script>
export default {
data() {
return {
title: 'Hello',
networkPreviewUrl: 'https://pic1.arkoo.com/56D0B40F99F841DF8A2425762AE2565D/picture/o_1i4qop009177v1tgf14db15he1iaj1is.jpg',
temporaryPreviewUrl: '',
previewUrl: '',
nodesStr: '<p>---</p>'
}
},
onLoad() {
},
methods: {
// 下载
downloadImage(){
uni.downloadFile({
url: this.networkPreviewUrl,
filePath: '/CacheFilePath/',
timeout: 0,
success(res) {
this.temporaryPreviewUrl = res.tempFilePath
console.log('下载:', res.tempFilePath)
}
})
},
// 保存
saveImage(){
const fs = uni.getFileSystemManager()
fs.saveFile({
tempFilePath: this.temporaryPreviewUrl,
success(res) {
this.previewUrl = res.savedFilePath
this.nodesStr = `<p>发斯蒂芬</p><img src="${this.previewUrl}" alt="" /><img src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/cloud@2x.jpg" width="20" height="20"/>`
console.log('保存:', res.savedFilePath)
}
})
}
}
</script>
<style>
.logo {
height: 100px;
width: 100px;
margin: 100px auto 25px auto;
}
.title {
font-size: 18px;
color: #8f8f94;
text-align: center;
}
.image-dom {
width: 300rpx;
height: 300rpx;
}
</style>
更多关于uni-app 富文本标题rich-text不能渲染img标签src是本地文件地址的图片的实战教程也可以访问 https://www.itying.com/category-93-b0.html
6 回复
直接使用网络地址
更多关于uni-app 富文本标题rich-text不能渲染img标签src是本地文件地址的图片的实战教程也可以访问 https://www.itying.com/category-93-b0.html
由于业务需要,要保证在没有网络的情况下保证页面的初始显示要正常,只能使用本地缓存的数据,没法使用网络地址
回复 杨婆婆管家家: 试过再将图片转 base64 使用吗
你报的到底是nvue的问题,还是uni-app x的问题?
uni-app x的问题,在hx的帮助菜单里报bug
已经报过了
在uni-app中,rich-text组件确实无法直接渲染本地文件路径的图片。这是因为rich-text组件在渲染时,img标签的src属性需要是网络URL或base64格式的数据,而不能是本地文件路径(如/storage/emulated/...这样的路径)。
从你的代码可以看到:
- 网络图片
https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/cloud@2x.jpg能够正常显示 - 但保存到本地的图片路径
this.previewUrl无法渲染
解决方案是将本地图片转换为base64格式。你可以使用uni-app的API读取本地文件并转换为base64:
// 在saveImage方法中
saveImage() {
const fs = uni.getFileSystemManager()
fs.saveFile({
tempFilePath: this.temporaryPreviewUrl,
success: (res) => {
this.previewUrl = res.savedFilePath
// 读取本地文件并转换为base64
fs.readFile({
filePath: this.previewUrl,
encoding: 'base64',
success: (readRes) => {
const base64Data = `data:image/jpeg;base64,${readRes.data}`
this.nodesStr = `<p>发斯蒂芬</p><img src="${base64Data}" alt="" width="300" height="300"/><img src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/cloud@2x.jpg" width="20" height="20"/>`
}
})
}
})
}

