生活随笔
收集整理的這篇文章主要介紹了
uniapp 图片上传
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言:此功能中用到了uview中的Upload 上傳 組件,所以需要在項目中引入uview,如果未引入可以參考我前面文章uniapp 引入 uview,已經引入的小伙伴請繼續看!
整體思路:
第一步:創建上傳按鈕。
第二步:創建彈框,上傳圖片功能在彈框內,先為隱藏狀態。
當點擊上傳按鈕,顯示彈框,上傳圖片。
第三步:復制uview組件代碼,這里我加了一個圖片格式判斷。
第四步:把uview組件代碼中的接口地址改為自己項目的接口。
第五步:完成。
查看更多Upload 上傳 組件配置項:查看更多
上代碼:
<template
><view
><!-- 上傳圖片 按鈕
--><view
class="" ><u
-button type
="primary" @click
="commit1" color
="#3261FC" customStyle
="width: 200rpx; margin-top: 20rpx;height: 80rpx;" text
="上傳圖片"></u
-button
></view
><!-- 提示
--><view
class="">請上傳jpg
,png格式的圖片,其他格式暫不支持
</view
><!-- 圖片底部彈出框 開始
--><u
-popup
:show
="show1" closeable
="true" @close
="close1" @open
="open1"><u
-upload
:fileList
="fileList1"customStyle
="margin-left: 30rpx;margin-top: 60rpx;"@afterRead
="afterRead"@
delete="deletePic"name
="1"multiple:maxCount
="2"></u
-upload
></u
-popup
><!-- 圖片底部彈出框 結束
--></view
>
</template
><script
>export default {data() {return {show1:false,fileList1: [],fileList2s:[],}},methods: {commit1(){this.show1
=true;},close1() {this.show1
= false;},open1() {},deletePic(event) {console
.log(event
.index
);this[`fileList${event.name}`].splice(event
.index
, 1)},async afterRead(event) {var path
= event
.file
[0].url
;var suffix
= path
.substr(path
.lastIndexOf('.'));var lowerSuffic
= suffix
.toLowerCase()if(lowerSuffic
=== '.jpg' || lowerSuffic
=== '.png' ){let lists
= [].concat(event
.file
)let fileListLen
= this[`fileList${event.name}`].length
;console
.log(fileListLen
,'name的意思');lists
.map((item) => {this[`fileList${event.name}`].push({...item
,status: 'uploading',message: '上傳中'})})for (let i
= 0; i
< lists
.length
; i
++) {const result
= await this.uploadFilePromise(lists
[i
].url
)let item
= this[`fileList${event.name}`][fileListLen
]this[`fileList${event.name}`].splice(fileListLen
, 1, Object
.assign(item
, {status: 'success',message: '',url: result
}))fileListLen
++}}else{uni
.showToast({icon:'error',title: '圖片格式有誤',duration: 2000});}},uploadFilePromise(url) {console
.log(url
,'圖片臨時路徑');return new Promise((resolve, reject) => {let a
= uni
.uploadFile({url: '真實的接口地址', filePath: url
,name: 'file',formData: {user: 'test'},success: (res) => {console
.log(res
,'成功回調');setTimeout(() => {resolve(res
.data
.data
)}, 1000)}});})}}}
</script
><style
></style
>
總結
以上是生活随笔為你收集整理的uniapp 图片上传的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。