vue 上传图片到阿里云(前端直传:不推荐)

vue

为何要这样做:减轻后端数据库压力(个人觉得于前端没啥用,谁返回来都行)


代码部分:

<template>

<div class="upLoad">

<div class="file">上传图片

<input type="file" :accept="typeArr" @change="upload($event)">

</div>

</div>

</template>

<style lang="less" scoped>

.file {

position: relative;

left: .26rem;

top: .2rem;

display: inline-block;

background: #32d582;

border: 1px solid #99D3F5;

border-radius: 4px;

padding: 4px 12px;

overflow: hidden;

color: white;

text-decoration: none;

text-indent: 0;

line-height: 20px;

}

.file input {

position: absolute;

font-size: 100px;

right: 0;

top: 0;

opacity: 0;

}

</style>

<script>

export default{

props: [\'typeArr\', \'size\'],

data(){

return {

client: \'\',

fileSize: 5000000

}

},

methods: {

getRight(){

if (this.size) {

this.fileSize = this.size;

}

this.client = new OSS.Wrapper({

region: "同endpoint",

secure: true,//https

endpoint: \'运维会告诉你\',

accessKeyId: "id和secret去阿里云控制台获得",

/*accessKeyId,accessKeySecret两者到阿里云控制台获得*/

accessKeySecret: "",

bucket: \'\' /*装图片的桶名*/

});

},

/**上传图片**/

upload(event){

var self = this;

var file = event.target.files[0];

var type = file.name.split(\'.\')[1];

var storeAs = new Date().getTime() + \'.\' + type;

var boolean = true;

if (file.size > this.fileSize) {

Toast(\'亲,图片不能超过!\' + this.fileSize / 1000 + \'kb\');

return false;

}

if (this.typeArr && this.typeArr.indexOf(type) > 0) {

boolean = false;

}

if (boolean) {

Toast(\'上传图片格式不支持!请选择\' + this.typeArr);

return false;

}

this.getRight();

this.client.multipartUpload(storeAs, file).then(function (result) {

console.log(result)//至此就拿到了返回的路径

self.data.url = result.res.requestUrls[0].split(\'?\')[0];

}).catch(function (err) {

console.log(err);

});

},

}

}

</script>

父组件调用

<up-Load class="files" typeArr="image/png,image/jpg,image/gif,image/jpeg" size="500000">

</up-Load>

注:需引入官网推荐的oss对象的cdn

<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>

需再次强调的是:该代码为前端直传,accessKeyId,accessKeySecret都暴露在外面,更安全的方法可见官网的“服务端签名后上传”(貌似没示例)

原文地址:https://segmentfault.com/a/1190000013153127

以上是 vue 上传图片到阿里云(前端直传:不推荐) 的全部内容, 来源链接: utcz.com/z/374564.html

回到顶部