var CosAuth = require('./cos-auth');
var Bucket = 'examplebucket-1250000000';
var Region = 'ap-shanghai';
var ForcePathStyle = false;
var uploadFile = function () {
var prefix = 'https://' + Bucket + '.cos.' + Region + '.myqcloud.com/';
if (ForcePathStyle) {
prefix = 'https://cos.' + Region + '.myqcloud.com/' + Bucket + '/';
}
var camSafeUrlEncode = function (str) {
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\\(/g, '%28')
.replace(/\\)/g, '%29')
.replace(/\\*/g, '%2A');
};
var stsCache;
var getCredentials = function (callback) {
if (stsCache && Date.now() / 1000 + 30 < stsCache.expiredTime) {
callback(data.credentials);
return;
}
wx.request({
method: 'GET',
url: 'https://example.com/sts.php',
dataType: 'json',
success: function (result) {
var data = result.data;
var credentials = data.credentials;
if (credentials) {
stsCache = data
} else {
wx.showModal({title: ‘임시 키 가져오기 실패’, content: JSON.stringify(data), showCancel: false});
}
callback(stsCache && stsCache.credentials);
},
error: function (err) {
wx.showModal({title: ‘임시 키 가져오기 실패’, content: JSON.stringify(err), showCancel: false});
}
});
};
var getAuthorization = function (options, callback) {
getCredentials(function (credentials) {
callback({
XCosSecurityToken: credentials.sessionToken,
Authorization: CosAuth({
SecretId: credentials.tmpSecretId,
SecretKey: credentials.tmpSecretKey,
Method: options.Method,
Pathname: options.Pathname,
})
});
});
};
var postFile = function (filePath) {
var Key = filePath.substr(filePath.lastIndexOf('/') + 1);
var signPathname = '/';
if (ForcePathStyle) {
signPathname = '/' + Bucket + '/';
}
getAuthorization({Method: 'POST', Pathname: signPathname}, function (AuthData) {
var requestTask = wx.uploadFile({
url: prefix,
name: 'file',
filePath: filePath,
formData: {
'key': Key,
'success_action_status': 200,
'Signature': AuthData.Authorization,
'x-cos-security-token': AuthData.XCosSecurityToken,
'Content-Type': '',
},
success: function (res) {
var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
console.log(res.statusCode);
console.log(url);
if (/^2\\d\\d$/.test('' + res.statusCode)) {
wx.showModal({title: ‘업로드 성공’, content: url, showCancel: false});
} else {
wx.showModal({title: ‘업로드 실패’, content: JSON.stringify(res), showCancel: false});
}
},
fail: function (res) {
wx.showModal({title: ‘업로드 실패’, content: JSON.stringify(res), showCancel: false});
}
});
requestTask.onProgressUpdate(function (res) {
console.log(‘진행률:’, res);
});
});
};
var putFile = function (filePath) {
var Key = filePath.substr(filePath.lastIndexOf('/') + 1);
var signPathname = '/' + Key;
if (ForcePathStyle) {
signPathname = '/' + Bucket + '/' + Key;
}
getAuthorization({Method: 'PUT', Pathname: signPathname}, function (AuthData) {
var wxfs = wx.getFileSystemManager();
wxfs.readFile({
filePath: filePath,
success: function (fileRes) {
var requestTask = wx.request({
url: prefix + signPathname.substr(signPathname.lastIndexOf('/') + 1),
method: 'PUT',
header: {
'Authorization': AuthData.Authorization,
'x-cos-security-token': AuthData.XCosSecurityToken,
},
data: fileRes.data,
success: function success(res) {
var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
if (res.statusCode === 200) {
wx.showModal({title: ‘업로드 성공’, content: url, showCancel: false});
} else {
wx.showModal({title: ‘업로드 실패’, content: JSON.stringify(res), showCancel: false});
}
console.log(res.statusCode);
console.log(url);
},
fail: function fail(res) {
wx.showModal({title: ‘업로드 실패’, content: JSON.stringify(res), showCancel: false});
},
});
requestTask.onProgressUpdate(function (res) {
console.log('진행 중:', res);
});
},
});
});
};
wx.chooseImage({
count: 1,
sizeType: ['original'],
sourceType: ['album', 'camera'],
success: function (res) {
putFile(res.tempFiles[0].path);
}
})
};
문제 해결에 도움이 되었나요?