微信小程式 上傳圖片視訊到阿里雲 附帶進度條
阿新 • • 發佈:2018-12-19
功能採用阿里雲PostObjectAPI進行上傳,優點:1,採用policy,Signature保證了賬號安全性
疑問:當在windows工具上開發沒有問題,但在手機上測試發現 --- 當上傳進度達到100還需要等好長時間才走到(success: res => )這一步,如果有人知道為什麼在下邊給弟弟留言吧。
設定進度條
<view style='{{display_}}'>
<progress percent="{{percent_}}" show-info />
</view>
一,choose圖片/視訊
業務需求這的fileName是使用者填寫的
//選擇圖片 upload_image_: function(fileName) { var this_ = this; wx.chooseImage({ success(res) { console.log("圖片資訊" + res) //判斷圖片大小 if (res.tempFiles[0].size > 1024 * 1024 * 20) { wx.showToast({ title: "圖片不能超過20M!", icon: 'none', duration: 1000 * 2, mask: true }) return; } //上傳 var filePath = res.tempFilePaths[0]; this_.upload_II_(fileName, filePath, res.tempFiles[0].size); } }) }, //選擇視訊 upload_video_: function(fileName) { var this_ = this; wx.chooseVideo({ sourceType: ['album', 'camera'], maxDuration: 60, camera: 'back', compressed: false, success(res) { console.log("視訊資訊-臨時路徑" + res.tempFilePath) console.log("視訊資訊-大小" + res.size) console.log("視訊資訊-時長" + res.duration) if (res.size > 1024 * 1024 * 200) { wx.showToast({ title: "視訊不能超過200M!", icon: 'none', duration: 1000 * 2, mask: true }) return; } this_.upload_II_(fileName, res.tempFilePath, res.size); } }) },
二,獲取相關阿里雲oss賬號資訊
//【1】獲取oss資訊 wx.request({ url: 'xxxxxxxxxx/ossinfo', method: 'POST', success: res => { if (res.statusCode == 200 && res.data.status == 0) { res = res.data; var accessid = res.data.accessid; var policy = res.data.policy; var signature = res.data.signature; var fPath = res.data.fPath; var expire = res.data.expire; var uploadUrl = res.data.uploadUrl; } } })
這裡的相關返回值signature 等可以純在page.data裡也可以直接使用,看實際情況吧。
後端是用java寫的 大致給一個參考:
@RequestMapping("{openId}/ossinfo")
@ResponseBody
public JSONObject ossinfo(@PathVariable String openId) {
JSONObject body = new JSONObject();
try {
JSONObject data = new JSONObject();
//過期時間 3分鐘
long eTime = System.currentTimeMillis() + 1000 * 60 * 3;
String eTimeStr = DateUtil.formatIso8601Date(new Date(eTime));
//檔案大小限制
long maxSize = 1024 * 1024 * 200;
String policy = "{\"expiration\": \"" + eTimeStr + "\",\"conditions\": [[\"content-length-range\", 0, " + maxSize + "]]}";
String encodePolicy = new String(Base64.encodeBase64(policy.getBytes()));
// 生成簽名。
String signaturecom = ServiceSignature.create().computeSignature(AliyunOssProperties.getAccessKeySecret(), encodePolicy);
//檔案儲存路徑 按照自己的情況填寫吧
String fPath = UUID.randomUUID().toString();
data.put("accessid", AliyunOssProperties.getAccessKeyId());
data.put("policy", encodePolicy);
data.put("signature", signaturecom);
data.put("expire", eTime);
data.put("fPath", fPath);
//相應的阿里雲伺服器
data.put("uploadUrl", "https://buguohe.oss-cn-beijing.aliyuncs.com");
body.put("data", data);
body.put("status", 0);
body.put("msg", "成功");
} catch (Exception e) {
body.put("status", -1);
body.put("msg", "異常錯誤");
logger.error(e.getMessage(), e);
}
return body;
主要是這三個引數
accessid阿里雲身份標識 ;
policy 經過Base64編碼了的相關設定 ;
signature 簽名身份驗證
三,上傳到阿里雲
upload_II_: function(fileName, filePath, fileSize) {
wx.showToast({
title: '正在上傳',
icon: 'loading',
duration: 1000 * 100,
mask: true
})
var this_ = this;
//【1】獲取oss資訊
wx.request({
url: 'xxxxxx/ossinfo',
data: {
fileSize: fileSize
},
method: 'POST',
success: res => {
if (res.statusCode == 200 && res.data.status == 0) {
res = res.data;
var accessid = res.data.accessid;
var policy = res.data.policy;
var signature = res.data.signature;
var fPath = res.data.fPath;
var expire = res.data.expire;
var uploadUrl = res.data.uploadUrl;
//【2】上傳檔案
var fType = filePath.substring(filePath.lastIndexOf("."), filePath.length);
console.log("型別 :" + fType);
//業務邏輯拼 key 和檔名稱
fileName = fileName + fType;
fPath = fPath + '/' + fileName;
console.log(babyData);
//這裡是進度條
this_.setData({
percent_: 0,
display_: "display: block;"
});
const uploadTask = wx.uploadFile({
url: uploadUrl,
formData: {
'Filename': fileName,
'Content-Disposition': 'filename=' + fileName, //檔案描述 這裡可以設定直接下載
還是可以線上檢視
'key': fPath, //key 是阿里雲儲存路徑
'policy': policy,
'OSSAccessKeyId': accessid,
'success_action_status': '200', //讓服務端返回200,不然,預設會返回204
'signature': signature
},
name: 'file',
filePath: filePath,
header: {
'content-type': 'multipart/form-data;boundary=' + fileSize
},
success: res => {
console.log(res);
console.log("UPLOAD : " + new Date());
if (res.statusCode == 200) {
//上傳成功
//訪問地址
console.log(uploadUrl+fPath);
wx.showToast({
title: '上傳成功',
icon: 'success',
duration: 1000 * 1,
mask: true
})
//進度條
this_.setData({
percent_: 100
});
} else {
//系統錯誤
wx.showToast({
title: '系統錯誤!',
icon: 'none',
duration: 1000 * 2,
mask: true
})
}
}
})
uploadTask.onProgressUpdate((res) => {
console.log('上傳進度', res.progress + " " + new Date())
console.log('已經上傳的資料長度', res.totalBytesSent)
console.log('預期需要上傳的資料總長度', res.totalBytesExpectedToSend)
console.log(new Date());
this_.setData({
percent_: res.progress - 1
});
})
} else {
var msg = '系統錯誤!';
if (res.data.msg) {
msg = res.data.msg;
}
//系統錯誤
wx.showToast({
title: '系統錯誤!',
icon: 'none',
duration: 1000 * 2,
mask: true
})
}
}
})
},