1、从客户端会话选择文件 wx.chooseMessageFile
布局
<view>
<view catchtap="formUploadFile" data-name="uploadFile">
<button size="mini">上传文档附件</button>
<view class="">(上传格式为PDF、EXCEL、WORD)</view>
</view>
<view class="">6份以内</view>
</view>
<view wx:for="{{fileUrlArr}}" wx:key="value">
<view catchtap="formUploadFilePreview" data-path="{{item.path}}" data-name="uploadFile">
<view class="">{{item.title}}</view>
</view>
<view catchtap="formUploadFileDel" data-path="{{item.path}}" data-name="uploadFile">
<text class="peafowlIconfont peafowl-close-circle"></text>
</view>
</view>
方法:上传
formUploadFile(e){
wx.chooseMessageFile({
count: 2,
type: 'file',
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFiles;
if (!tempFilePaths || tempFilePaths.length <= 0) {
return;
};
upload(tempFilePaths);
},
fail(res) {
wx.showToast({
title: JSON.stringify(res),
icon: 'error',
duration: 2000
})
}
})
function upload(paths) {
wx.uploadFile({
url: 'https:xxxxxxxxxxxx',
filePath: paths[0].path,
name: 'file',
success: function (res) {
let url = _this.data.fileUrlArr;
let title = paths[0].name;
url.push({
path: paths[0].path,
title: title
});
_this.setData({
'fileUrlArr': url
});
},
fail: function () {
wx.showToast({
title: '上传失败',
icon: 'error',
duration: 2000
})
},
complete: function () {
paths.splice(0, 1);
if (paths.length > 0) {
upload(paths);
};
}
});
});
};
方法:删除
formUploadFileDel(e){
let n = e.currentTarget.dataset.name;
let path = e.currentTarget.dataset.path;
let value = this.data.fileUrlArr;
let filterValue = value.filter(function (element, index, self) {
return element.path != path;
});
_this.setData({
'fileUrlArr': filterValue
});
};
方法:预览
formUploadFilePreview(e) {
let filePath = e.currentTarget.dataset.path;
if (!filePath) {
return;
};
wx.downloadFile({
url: filePath,
success(res) {
if (res.statusCode === 200) {
var Path = res.tempFilePath //返回的文件临时地址,用于后面打开本地预览所用
wx.openDocument({
filePath: Path,
showMenu: true,
success: function (res) {
console.log('打开成功');
}
})
}
}
})
};