首先引入相关文件。
这边通过时间来命名文件名称,防止文件名重复。
这边配置oss的相关信息,没有可以去申请
完整代码:
var client = new OSS.Wrapper({
region: 'oss-cn-hangzhou',
accessKeyId: '*****************',
accessKeySecret: '******************************',
bucket: '************'
});
function timestamp() {
var time = new Date();
var y = time.getFullYear();
var m = time.getMonth() + 1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
console.log(y);
return "" + y + add0(m) + add0(d) + add0(h) + add0(mm) + add0(s);
}
function add0(m) {
return m < 10 ? '0' + m : m;
}
function getCaption(obj, state) {
var index = obj.lastIndexOf("?");
if (state == 0) {
obj = obj.substring(0, index);
} else {
obj = obj.substring(index + 1, obj.length);
}
return obj;
}
vm.upload = function(e) {
console.log(e.value)
var files = e.files[0]
var val = e.value
var filename = files.name;
var filesize = files.size;
var suffix = val.substr(val.indexOf("."));
var storeAs = timestamp() + suffix;
client.multipartUpload(storeAs, files).then(function(result) {
var urls = result.res.requestUrls[0]
if (urls.indexOf("?") != -1) {
urls = getCaption(urls, 0)
console.log(urls)
} else {
urls = result.res.requestUrls[0]
console.log(urls)
}
$.ajax({
url: "*****************************",
type: 'post',
dataType: 'json',
data: {
operation_type: "add_file_info",
version_id: "1.0",
file_name: storeAs,
file_download_url: urls
},
success: function(e) {
if(e.result_code==0){
alert('上传成功')
}
},
error: function(e) {
console.log(e.err_msg)
}
})
}).catch(function(err) {
console.log(err);
});
}