1.js使用
import { useOss } from '../utils/oss'
let ossUrl = await useOss('http://tmp/BOyneTlXF8TL5936e05540a6b0e5c2d4ffe31ccfac84.pngx-oss-process=style)
//http://tmp/BOyneTlXF8TL5936e05540a6b0e5c2d4ffe31ccfac84.pngx-oss-process=style是使用微信api上传后得到地址
2.使用这个地址上传到阿里云(可直接复制到js里后使用import加载到对应wxml里使用)
const baseUrl = 'http地址'
//定义request
function request(options){
return new Promise((resolve,reject)=>{
wx.request({
url: baseUrl + options.url,
method:options.method || 'get',
data:options.data || {},
header:{
"content-type":options.contenttype
},
timeout: '10000',
success (res) {
const {code, resCode} = res.data
if (code === 200 || code === 201 || resCode === '0000') {
resolve(res)
}
if (code === 402) {
return wx.navigateTo({
url: '/pages/login/login',
})
}
resolve(res)
},
fail (err) {
console.log(err, 'fail')
reject(err)
}
})
})
}
export async function useOss(file){
const res = await getAliyunAccess()
const {
resCode,
resultContent: ossParams
} = res.data
if (resCode === '0000') {
const {dir, accessid, policy, signature, callback, host: url} = ossParams
const timestamp = new Date().getTime()
const random = Math.floor(Math.random() * 100000);
const key = dir +''+ timestamp + "_" + random
const uploadRes = await uploadFile(key, accessid, policy, signature, callback, 200, url, file)
const object = JSON.parse(uploadRes.data)
const { filename } = object.resultContent
// console.log('这里是oss返回数据',filename)
return filename
}
}
//获取阿里云签名
function getAliyunAccess(){
return request({
url: '/aliyun/oss/policy',
method: 'GET',
contenttype: "application/x-www-form-urlencoded",
})
}
//上传图片到阿里云
function uploadFile(key, accessid, policy, signature, callback, success_action_status, url, file) {
return new Promise((resolve, reject) => {
wx.uploadFile({
url: url,
filePath: file,
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded',
},
name: 'file',
formData: {
'key': key,
'OSSAccessKeyId': accessid,
'policy': policy,
'Signature': signature,
'callback': callback,
'success_action_status': success_action_status
},
success(res) {
resolve(res)
},
fail(err) {
reject(err);
},
})
})
}