1、封装Api 列表 (文件名:apiUrlList.js)
var apiUrlList = {
service: "https://www.cnblogs.com/", //服务器
picUrl:'/static/images/',//图片地址
"upPic": { url: "/api/file/images",method: "POST",name:"图片上传"},
}; export default apiUrlList
2、封装 文件上传(文件名:upFile.js )
/**=====================================================================核心:接口文件====*/ import apiUrlList from "./apiUrlList.js" /**=====================================================================核心:网络请求====*/ /** * 功能:upFile("文件选择结果(文件本地路径)","提示文本") * 数据类型:upFile("字符串|必填","字符串|选填") * 实例:upFile("blob:http://www.****.cn/4a5caa1d-1cb5-45d5-89d7-0b9b92d4843a","图片") * */ function upFile(upFileUrl,upName){ let that=this; uni.showLoading({ title: '准备上传'+upName, mask:true }); var data={ 'file':upFileUrl, 'token': uni.getStorageSync('landingInfo').token }; return new Promise(function (resolve, reject) { console.log(apiUrlList.service + apiUrlList.upPic.url); const uploadTask=uni.uploadFile({ url: apiUrlList.service + apiUrlList.upPic.url, //接口地址 filePath: upFileUrl,//上传文件地址 name: 'file', formData: data, success: (res) => { resolve(JSON.parse(res.data));//成功返回,resolve是Promise的回调方式 }, fail(res) { wx.showToast({ title: '网络请求失败', icon: 'none', duration: 5000, mask:true }); reject(res);//失败返回,resolve是Promise的回调方式 }, complete(res){ uni.hideLoading(); if (JSON.parse(res.data).code == 2) {//判断登录 that.$appLanding(); return false } console.warn( "%c 备注:", 'color:red;font-size:15px','上传'+upName, "\n 提交地址:", apiUrlList.service + apiUrlList.upPic.url, "\n 提交data:", data, "\n 请求返回", JSON.parse(res.data)); } }); uploadTask.onProgressUpdate((res) => { uni.showLoading({ title: '上传进度:'+res.progress+"%", mask:true }); console.log('上传进度' + res.progress); console.log('已经上传的数据长度:' + res.totalBytesSent); console.log('预期需要上传的数据总长度:' + res.totalBytesExpectedToSend); }) }) } /**=====================================================================核心:开放入口函数====*/ export default upFile