💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
> app中图片上传是经常用到的功能 * [图片上传](https://www.kancloud.cn/wangking/uniapp/1877790#_4) * [头像上传](https://www.kancloud.cn/wangking/uniapp/1877790#_65) * [图片缓存](https://www.kancloud.cn/wangking/uniapp/1877790#_69) ## 图片上传 > 使用[文件上传:uni.uploadFile()](https://uniapp.dcloud.io/api/request/network-file?id=uploadfile)方式 ~~~ <template> <view class="content"> <progress :percent="percent" strock-width="10"></progress> <button type="primary" @tap="upload">chooseImg</button> </view> </template> <script> // 注册一个进度条 var _self; export default { data() { return { percent:0 } }, onLoad() { _self = this; }, methods: { upload:function(){ uni.chooseImage({ count: 1, sizeType:['copressed'], success(res) { // console.log(res.tempFilePaths) // 如果设置可选多张,这里可打印多张图地址 //因为有一张图片, 输出下标[0], 直接输出地址 var imgFiles = res.tempFilePaths[0] console.log(imgFiles) // 上传图片 // 做成一个上传对象 var uper = uni.uploadFile({ // 需要上传的地址 url:'http://demo.hcoder.net/index.php?c=uperTest', // filePath 需要上传的文件 filePath: imgFiles, name: 'file', success(res1) { // 显示上传信息 console.log(res1) } }); // onProgressUpdate 上传对象更新的方法 uper.onProgressUpdate(function(res){ // 进度条等于 上传到的进度 _self.percent = res.progress console.log('上传进度' + res.progress) console.log('已经上传的数据长度' + res.totalBytesSent) console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend) }) } }) } } } </script> ~~~ ## 头像上传 > 比如用户资料修改,其展现方式与以上不同 > 可参考:[https://www.cnblogs.com/wo1ow1ow1/p/11730220.html](https://www.cnblogs.com/wo1ow1ow1/p/11730220.html) ## 图片缓存 > 使用[文件下载:uni.downloadFile()](https://uniapp.dcloud.io/api/request/network-file?id=downloadfile)方式 ~~~ <template> <view class="content"> <image :src="imgUrl4display"></image> </view> </template> <script> var _self; export default { data() { return { imgUrl4display: '', imgRemoteUrl: 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/images/shuijiao.jpg' } }, onLoad() { _self = this; let keyName = 'image_storage'; uni.getStorage({ key: keyName, success: function(res) { console.log('get storage success...'); _self.displayImg(res.data); }, fail: function(res) { console.log('fail 2 download...'); // 本地没有缓存 需要下载 uni.downloadFile({ url: _self.imgRemoteUrl, success: (res) => { console.log(res) if (res.statusCode === 200) { _self.displayImg(res.tempFilePath); uni.setStorage({ key: keyName, data: res.tempFilePath, success: function() { } }) } } }); } }) }, methods: { displayImg: function(data) { _self.imgUrl4display = data; } } } </script> ~~~