.wxss代码
/* 小程序按钮样式 */
.btnImg1{
margin-top: 8rpx;
width: 70rpx;
height: 60rpx;
}
.cornerbutton_add {
display: flex; justify-content: center; /* 垂直居中 */
align-items: center; /* 水平居中 */ height: 45px;
margin-top: 45rpx;
border-radius: 20px;
background: #175acb;
color: white;
border: none;
}
.js 代码
addFile: function(){ //添加文件
wx.chooseMessageFile({//调用选择文件接口
count:Number(1),//文件数量
type: 'file',
success (res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFiles
console.log('选择',res);//这里log一下res的值
console.log(tempFilePaths);
tempFilePaths.forEach(i=>{
console.log(i);
wx.uploadFile({//调用上传文件接口
url: request.API + "/fileUpload/upload-image", //这个接口是后台给的
filePath: i.path,
name:'file',
method:"post",
header: {//headers记住传Authorization也就是token值,不然会返回401未登录
"content-type": "multipart/form-data",
"Authorization": wx.getStorageSync("token")
},
success (res){
console.log(res);
//上传成功后的一些操作
wx.hideLoading();
let rs = JSON.parse(res.data);
if (rs.code == 0) {
var str=rs.data.path
console.log(str);
var newStr = str.slice(0,4)+'s'+str.slice(4)
// console.log(newStr);
const k = `${e.target.dataset.type}[${
e.target.dataset.key
}].filevalue`;
for(var i=0;i<tempFilePaths.length;i++){
files.push({name:tempFilePaths[i].name,path:newStr})
}
// files.push({name:tempFilePaths[0].name,path:newStr})
that.setData({
[k]:files,
files:files,
})
console.log(that.data.three);
} else {
that.setData({
// isshow: true,
message: "上传失败,稍后重试"
});
setTimeout(() => {
that.setData({
//isshow: false,
message: ""
});
}, 2500);
}
}
})
})
}
})
},
预览文件的实现代码
wx.downloadFile({
url: e.currentTarget.dataset.path, // 要下载文件的路径
success: function (res) {
console.log(res);
let filePath = res.tempFilePath; //微信临时文件路径
console.log(filePath);
wx.openDocument({
filePath: filePath,
showMenu: false, //是否显示右上角菜单按钮 默认为false
success: function (res) {
console.log('打开网络文档成功')
},
fail: function(error){
console.log("打开网络文档失败")
}
})
}
})
wx.chooseMessageFile()用来选择文件,下面附上其可用属性
wx.upLoadFile()用来上传文件,下面附上其可用属性
下载文件和打开文件
wx.downloadFile下载文件,下面附上其可用属性
wx.openDocument 打开文件,下面附上其可用属性以及可打开的文件类型可打开的文件类型:
官方文档
选择文件: https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseMessageFile.html
上传文件:https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html
下载文件:https://developers.weixin.qq.com/miniprogram/dev/api/network/download/wx.downloadFile.html
打开文件:https://developers.weixin.qq.com/miniprogram/dev/api/file/wx.openDocument.html