功能采用阿里云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 签名身份验证
还有过期时间 要对应GMT时间
三,上传到阿里云
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
})
}
}
})
},