uni-app 图片缓存

<template>
	<image :src="img_url" :mode="mode" :lazy-load="lazyLoad" :style="setStyle"></image>
</template>

<script>
	export default {
		name: 'image-cache',
		props: {
			mode: {
				type: String,
				default: ''
			},
			lazyLoad: {
				type: Boolean,
				default: false
			},
			imgSrc: {
				type: String,
				default: '',
			},
			defaultImg: {
				type: String,
				default: ''
			},
			setStyle: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				img_url: ''
			}
		},
		watch: {
			imgSrc: {
				handler: function(n) {
					//console.log(n);
					var the = this;
					if (String(n).trim() === '') {
						the.img_url = the.defaultImg;
						return
					}
					//console.log("========> " + n);
					if(n.startsWith("/static/"))
					{
						the.img_url = n;
						return;
					}

					// #ifdef H5
						// 引起 跨域的问题, 开发环境
						the.img_url = n;
						return;
					// #endif

					//console.log("======================= imgSrc ============== ");
					var needCache = false;
					// #ifdef APP-PLUS | H5 | APP-VUE | APP-NVUE | APP-PLUS-NVUE
						needCache = true;
					// #endif
					//console.log("======================= need cache = ", needCache);
					if(!needCache)
					{
						the.img_url = n;
						return;
					}

					uni.getStorage({
						key: the.imgSrc,
						success: function(res) {
							if (res.data != '') {
								the.img_url = res.data;
							} else {
								uni.downloadFile({
									url: the.imgSrc,
									success: (ress) => {
										if (ress.statusCode === 200) {
											uni.setStorage({
												key: the.imgSrc,
												data: ress.tempFilePath,
												success: function() {

												}
											})
											the.img_url = ress.tempFilePath;
										} else {
											the.img_url = the.defaultImg;
										}
									},
									fail: () => {
										the.img_url = the.defaultImg;
									}
								});
							}
						},
						fail: function(res) {
							uni.downloadFile({
								url: the.imgSrc,
								success: (ress) => {
									if (ress.statusCode === 200) {
										uni.setStorage({
											key: the.imgSrc,
											data: ress.tempFilePath,
											success: function() {

											}
										})
										the.img_url = ress.tempFilePath;
									} else {
										the.img_url = the.defaultImg;
									}
								},
								fail: () => {
									the.img_url = the.defaultImg;
								}
							});
						}
					})
				},
				immediate: true
			}
		}
	}
</script>

使用

<pg-image-cache :imgSrc="mSingleImgUrl"></pg-image-cache>

服务端上传文件代码

spring boot 上传文件

上传图片需要压缩图片