之前公司需要寫(xiě)rn和小程序,由于公司圖片存儲(chǔ)用的是阿里的oss,但oss沒(méi)有對(duì)應(yīng)的sdk,所以開(kāi)始的時(shí)候遇到不少的坑,后來(lái)發(fā)現(xiàn)可以通過(guò)PostObject使用表單上傳文件到OSS。話不多說(shuō),直接上代碼:
/**
*
* @param imgPath 圖片路徑
* @param success 成功回調(diào)
* @param fail 失敗回調(diào)
* @constructor
*/
export const OssUpload = (imgPath: string, success: Function, fail: Function) => {
AsyncGet(ApiModule.utilityModel.oss_token, {}, true).promise.then((data) => {
const {
accessid,
host,
policy,
signature,
dir,
} = data;
let name = globalData.userId + "_" + fGetTs() + "." + 'jpg';
let file = {uri: imgPath, type: 'application/octet-stream', name: name};
let formData = new FormData();
formData.append('key', dir + name);
formData.append("OSSAccessKeyId", accessid);
formData.append("policy", policy);
formData.append("Signature", signature);
formData.append("file", file);
fetch(host, {
method: 'post',
'Content-Type': 'multipart/form-data; boundary=----theriverswine2017',
body: formData,
}).then((data) => {
LOG("圖片上傳成功");
LOG(JSON.stringify(data));
success(name);
}).catch((error) => {
LOG('圖片上傳失敗' + JSON.stringify(error));
fail(error);
})
}).catch((error) => {
LOG('圖片上傳失敗' + JSON.stringify(error));
fail(error);
})
};
參數(shù)介紹
| 參數(shù) | 描述 |
|---|---|
| key | 上傳文件的名稱(chēng) |
| OSSAccessKeyId | Bucket 擁有者的Access Key Id |
| policy | policy規(guī)定了請(qǐng)求的表單域的合法性。不包含policy表單域的請(qǐng)求被認(rèn)為是匿名請(qǐng)求,并且只能訪問(wèn)public-read-write的bucket。 |
| Signature | 根據(jù)Access Key Secret和policy計(jì)算的簽名信息,OSS驗(yàn)證該簽名信息從而驗(yàn)證該P(yáng)ost請(qǐng)求的合法性。 |
| file | 文件或文本內(nèi)容,必須是表單中的最后一個(gè)域 |
更詳細(xì)的參數(shù)可以參閱官方文檔
小程序的上傳
/**
* 上傳頭像
*/
function uploadPortrait(imgPath, success, fail) {
sendGetRequest('utils/oss_token_web', {}, true).then(result => {
const {
accessid,
host,
policy,
signature,
dir,
} = result;
var ts = Url.fGetTs();
let name = ts + "." + 'jpg';
wx.uploadFile({
url: 'https://' + host,
filePath: imgPath,
name: 'file',
formData: {
'key': dir + name,
'OSSAccessKeyId': accessid,
'policy': policy,
'Signature': signature,
}, success: function (res) {
console.log('成功')
console.log(res)
if (res.statusCode == 204) {
success(dir + name)
} else {
fail('網(wǎng)絡(luò)連接失敗')
}
}
, fail: function (res) {
console.log('失敗了')
console.log(res)
fail('網(wǎng)絡(luò)連接失敗')
}
})
}).catch(error => {
fail('網(wǎng)絡(luò)連接失敗')
})
}
可以看出小程序和js的上傳基本一致,只是需要用微信自帶的wx.uploadFile APi。但小程序的上傳請(qǐng)注意:
一定要在微信公眾平臺(tái)的后臺(tái)配置上傳路徑。具體步驟:
1.登錄https://mp.weixin.qq.com/
2.

image
若上傳失敗,可根據(jù)返回的錯(cuò)誤信息,在官網(wǎng)的錯(cuò)誤列表上找下,找出原因。
我在小程序上遇到的bug
小程序在上傳圖片的時(shí)候,有時(shí)候第一次上傳會(huì)出現(xiàn)上傳失敗,返回為:
{statusCode:400,data:"",errMsg:"uploadFile:ok"}。
statusCode為400,但沒(méi)有錯(cuò)誤信息,完全不知道為什么出錯(cuò)。重新上傳又好了,若有大佬知道,請(qǐng)教教小弟。