uni封装上传图片/文件

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,
                        "
 提交地址:",   apiUrlList.service + apiUrlList.upPic.url,
                        "
 提交data:",  data,
                        "
 请求返回", 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
封装 图片/文件上传

3、使用vue链 成为全局调用

import upFile from 'appConfig/upFile.js'; //引入 
Vue.prototype.$upFile =upFile   //申明 

Vue.prototype.$apiUrlList =apiUrlList ; //申明

4、在需要上传的位置

//选择图片
selectPic(){
let that=this;
uni.chooseImage({
count: 1, //最多可以选择的图片张数 默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
success: function (res) {
var selectPic=res.tempFilePaths;//文件选择结果(文件本地路径)
if(selectPic[0]!=0){
that.$upFile(selectPic[0],"图片").then((upFile) => {
if (upFile.code == 0) {

//服务端返回

} else {

}
}).catch((res) => {
uni.showToast({
title: '获取的数据出错',
icon: "none"
});
});
}
}
});
},

  

原文地址:https://www.cnblogs.com/caitangbutian/p/12937759.html