最近在寫小程序項目,碰到了一個需求,需要用戶可以上傳各種類型的文件和圖片,展示在頁面上,并且點擊還可以進(jìn)行預(yù)覽,就找了找微信小程序官網(wǎng),寫了一個例子,分享一下
直接看代碼:
wxml:
<view>
// 上傳按鈕
<button class="upload-btn" bindtap='uploadFile'>
<image src="../../../images/icon-upload.png"></image>上傳相關(guān)資料
</button>
// 展示
<view class="flex enclosure" wx:for="{{fileArray}}" wx:key="index">
<view class="flex" bindtap="previewFile" data-path="{{item.path}}">
// 通過filter根據(jù)不同類型展示不同圖片
<image style="width:80rpx;height:80rpx;margin-right: 18rpx;" src=
{{filters.picture(item.name)}}"></image>
// 文件名
<text style="width: 400rpx;overflow:hidden;text-overflow:ellipsis;white-
space:nowrap; ">{{item.name}}</text>
</view>
</view>
</view>
wxss:
// 樣式大家可以自己寫
.upload-btn {
height: 84rpx;
color: #5f9be7;
font-size: 28rpx;
background-color: rgba(95, 155, 231, 0.1);
display: flex;
align-items: center;
justify-content: center;
margin: 16rpx 0 36rpx;
}
.upload-btn image {
width: 34rpx;
height: 34rpx;
margin-right: 20rpx;
}
.flex {
display: flex;
align-items: center;
justify-content: space-between;
color: #666;
}
.enclosure {
margin-bottom: 40rpx;
}
js:文章來源:http://www.zghlxwxcb.cn/news/detail-527135.html
// 文件上傳
uploadFile() {
wx.chooseMessageFile({
count: 10, //選擇文件的數(shù)量
type: 'all', //選擇文件的類型
success: (res) => {
this.setData({
fileArray: this.data.fileArray.concat(res.tempFiles)
})
}
})
},
// 預(yù)覽附件
previewFile(e) {
var string = ''
string = e.currentTarget.dataset.path.substring(e.currentTarget.dataset.path.indexOf(".") + 1)
if (string == 'png' || string == 'jpg' || string == 'gif' || string == 'jpeg') {
// 圖片預(yù)覽
var arr = []
arr.push(e.currentTarget.dataset.path)
wx.previewImage({
current: e.currentTarget.dataset.path,
urls: arr
})
} else {
// 文件預(yù)覽
wx.openDocument({
fileType: string, // 文件類型
filePath: e.currentTarget.dataset.path, // 文件地址
success: function (res) {
console.log('成功')
},
fail: function (error) {
console.log("失敗")
}
})
}
},
有問題和建議歡迎大家留言文章來源地址http://www.zghlxwxcb.cn/news/detail-527135.html
到了這里,關(guān)于微信小程序上傳文件及圖片(可以預(yù)覽)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!