1.上一篇写了微信小程序图片的上传与预览功能,这一篇则记录下微信小程序的上传文件与下载文件的方法。
2.微信小程序上传文件用到了两个方法,首先调用了 wx.chooseMessageFile的方法调起了微信的聊天记录,从聊天记录中获取文件,(本打算是从本地储存的文件中获取要上传的文件,但是找了微信提供的api好像不能直接实现如果可以实现麻烦告知,万分感谢!嵌套H5也可以实现上传文件,这里就暂不讨论),上传文件获取本地路径,再调用wx.uploadFile的方法,将拿到的本地路径作为参数传给后端。
3.微信小程序的文件下载也提供了对应的api,wx.downloadFile参数为文件的地址,返回一个临时的地址tempFilePath,在通过wx.openDocument的方法打开文档
4.效果图
5.代码如下wxml
<view wx:if="{{path.length}}">
<view id="fileUpload" wx:for="{{path}}" wx:key="index">
<image id= "leftImage" src='../../assert/word.png' ></image>
<view id='centerContent'>{{ name[index] }}</view>
<view id='rightBtn'>
<view bindtap="delete" data-index="{{index}}" wx:if="{{only != 0}}">删除</view>
<view bindtap="downLoad" data-item="{{item}}">下载</view>
</view>
</view>
</view>
6.js代码如下 上传文件代码
uploadFile(){
const that = this
wx.chooseMessageFile({
count: 1, //能选择文件的数量
type: 'file', //能选择文件的类型,我这里只允许上传文件.还有视频,图片,或者都可以
success(res) {
var size = res.tempFiles[0].size;
var filename = res.tempFiles[0].name;
var newfilename = filename + "";
var fileTYpe = ['.xlsx', '.xls', '.doc', '.ppt', '.pdf',]
const bollen = fileTYpe.some(item=>{
return newfilename.indexOf(item) > 0
})
if (!bollen){ //我还限制了文件的大小和具体文件类型
wx.showToast({
title: '支持.xlsx/ .xls/ .doc/ .ppt/ .pdf格式文件',
icon: "none",
duration: 2000,
mask: true
})
}else{
// 拿到本地路径将其作为参数上传
console.log(res.tempFiles[0].path,filename);
wx.uploadFile({
url: baseURL + '/common/upload', // 上传接口
filePath: res.tempFiles[0].path,
header:{ Authorization: 'Bearer ' + wx.getStorageSync('token') },
name: 'file',
success (res){
const arr = that.data.path
const arrer = that.data.name
console.log(JSON.parse(res.data).newFileName);
arr.push(JSON.parse(res.data).url)
arrer.push(JSON.parse(res.data).newFileName)
that.setData({
path:arr,
name:arrer
})
console.log(arr,that.data.path);
}
})
}
}
})
},
7.js文件预览文件
downLoad(e){
// e为传递过来的参数
console.log(e.currentTarget);
let url = e.currentTarget.dataset.item
// 这里后台使用的是若依框架,在线上地址为http开头的,手动转为https开头
if(baseURL == 'https://453534453.com/prod-api'){
url = url.replace('http://','https://')
}
wx.downloadFile({
url: url,
// filePath: wx.env.USER_DATA_PATH + '/' + '上传成员.xlsx',
success: function (res) {
console.log(res)
const filePath = res.tempFilePath;
// 将实际地址转为本地路径,打开本地文件
wx.openDocument({
filePath: filePath,
showMenu: true,
// fileType: 'xlsx',
success: function (res) {
console.log('打开文档成功', res)
}
})
},
fail: function (err) {
console.log(err)
}
})
},
8.记录微信小程序上传文件,如果有哪些不对或者不妥之处还望指出,万分感谢!!