<view class="form-item">
一、视图
<view class="form-label">系统用印: <text class="required">*</text></view>
<view class="upload-area">
<view class="image-list-center">
<view class="image-preview-container" wx:for="{{imageUrls}}" wx:key="index">
<view class="image-item">
<image src="{{url}}{{item}}" mode="widthFix" class="preview-image"></image>
<icon
type="clear"
size="20"
class="delete-icon"
bindtap="removeImage"
data-index="{{index}}"
></icon>
</view>
</view>
<view class="upload-btn" wx:if="{{imageUrls.length < 1}}" bindtap="chooseImages">
<icon type="camera" size="40"></icon>
<text>点击上传图片</text>
</view>
</view>
<view class="format-tip">支持格式:jpg、jpeg、png</view>
</view>
</view>二、样式
/* 文件上传样式 */
.upload-container {
padding: 10rpx 0;
}
.upload-btn {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
padding: 24rpx 0;
border-radius: 8rpx;
background-color: #f2f3f5;
color: #1677ff;
font-size: 26rpx;
}
.file-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16rpx;
border: 2rpx solid #e5e6eb;
border-radius: 8rpx;
background-color: #fafafa;
}
.file-name {
flex: 1;
margin: 0 16rpx;
font-size: 24rpx;
color: #4e5969;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.remove-btn {
color: #f53f3f;
border-color: #f53f3f;
font-size: 22rpx;
padding: 6rpx 16rpx;
}
/* 文件格式提示样式 */
.file-format-tip {
color: #86909c;
font-size: 22rpx;
margin-top: 12rpx;
text-align: left;
padding-left: 4rpx;
line-height: 1.4;
}三、js
chooseFile() {
const that = this;
const allowedExtensions = ['pdf', 'doc', 'docx'];
wx.chooseMessageFile({
count: 1,
type: 'file',
extension: allowedExtensions,
success(res) {
const file = res.tempFiles[0];
// 手动校验文件后缀
const fileName = file.name;
// 获取文件后缀,转小写统一判断
const fileSuffix = fileName.split('.').pop().toLowerCase();
if (!allowedExtensions.includes(fileSuffix)) {
wx.showToast({ title:'不支持该格式文件', icon: 'none' });
that.setData({
statusText: `文件格式不支持,仅允许${allowedExtensions.join('、')}`,
tempFilePath: null,
fileInfo: {},
fileId: ''
})
return; // 终止后续赋值,不保存非法文件
}
// 格式合法,正常赋值
that.setData({
tempFilePath: file.path,
fileInfo: {
name: file.name,
size: file.size,
type: 'application/octet-stream'
},
statusText: `已选择文件:${file.name}`,
fileId: ''
});
},
fail(err) {
let msg = '';
if (err.errMsg.includes('cancel')) {
msg = '已取消选择'
} else {
msg = `仅支持上传${allowedExtensions.join('、')}格式的文件`
}
that.setData({
statusText: msg,
tempFilePath: null,
fileInfo: {},
fileId: ''
});
}
});
},
// 移除文件
removeFile() {
this.setData({
tempFilePath: null,
fileInfo: {},
fileId: '',
statusText: '文件已被移除'
});
},