serve.js//和请求一块封装
BASE_URL = ‘https:test.com/api‘//统一请求地址
export const uploadFile = (options) => { return new Promise((resolve, reject) => { console.log(‘options‘, options) let header = {} header[‘Content-Type‘] = "multipart/form-data" try { const value = uni.getStorageSync(‘token‘);//取存本地的token if (value) { header[‘token‘] = value } } catch (e) { // error } uni.uploadFile({ url: baseUrl + options.url, name: ‘file‘, filePath: options.filePath.img, header, success: (res) => { // return res resolve(res) //如果请求成功,调用resolve返回数据 }, }) }) }
upload_serve.js
import {uploadFile} from "./serve.js" export const upload = (data) => { return uploadFile({ url: "/test",//请求后缀 filePath: data, header: { ‘Content-Type‘: ‘multipart/form-data‘ } }) } //调用upload_server.js import {upload} from upload_serve.js uni.chooseImage({ count: 1, //默认9 sizeType: [‘original‘, ‘compressed‘], sourceType: [‘album‘], //从相册选择 success: function (chooseImageRes) { let img=chooseImageRes.tempFilePaths[0] upload({img}).then(res=>{ //直接通过uni.chooseImage获取地址传给后端 let resData=JSON.parse(res.data) console.log(resData) }) })
原文:https://www.cnblogs.com/geki/p/14820868.html