vue页面使用阿里oss上传功能(一)

源码

直奔主题:


注意:这里的前端代码是基于vue 1.0 的上传代码,如果您的项目使用的是vue2.0,那么请点击这里

前端部分

1.前端页面中需要引入oss-sdk:
<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>
2.自己封装的upload组件:

<template>
    <div>
        <div class="oss_file">
            <input type="file" :id="id" :multiple="multiple" @change="doUpload"/>
        </div>
    </div>
</div>
</template>
<script>
    export default{
        props:{
            multiple:{
                type: Boolean,
                twoWay:false
            },
            id:{
                type: String,
                twoWay:false
            },
            url:{
                type: Array,
                twoWay:true
            }
        },
        data(){
            return{
                region:'Your oss Region',
                bucket:'Bucket Name',
            };
        },
        methods:{
            doUpload(){
                const _this = this;
                Vue.http.get('/alioss/getOssToken').then((result) => {
                    const client = new OSS.Wrapper({
                        region:_this.region,
                        accessKeyId: result.data.token.AccessKeyId,
                        accessKeySecret: result.data.token.AccessKeySecret,
                        stsToken: result.data.token.SecurityToken,
                        bucket:_this.bucket
                    })
                    const files = document.getElementById(_this.id);
                    if(files.files){
                        const fileLen = document.getElementById(_this.id).files
                        const resultUpload = [];        
                        for (let i = 0; i < fileLen.length; i++) {
                            const file = fileLen[i];
                            const storeAs = file.name;
                            client.multipartUpload(storeAs, file, {

                            }).then((results) => {
                                if(results.url){
                                    resultUpload.push(results.url);
                                }
                            }).catch((err) => {
                                console.log(err);
                            });
                        }
                        _this.url = resultUpload;
                    }   
                });
            }
        }
    };
</script>
<style type="text/css">
    .oss_file {
        height: 100px;
        width: 100%;

    }
    .oss_file  input {
        right: 0;
        top: 0;
        opacity: 0;
        filter: alpha(opacity=0);
        cursor: pointer;
        width: 100%;
        height: 100%;
    }

</style>

3.使用组件:

<template>
    <div>
        <div>
            <ali-upload :url.sync="uploadUrl" :multiple="true" :id="uploadId" :code.sync="uploadCode"></ali-upload>
        </div>
        <div v-for="url in uploadUrl">
            ![](url)
        </div>
    </div>
</div>
</template>
<script>
    import aliUpload from './../components/aliossupload.vue';
    export default{
        components:{
            aliUpload
        },
        data(){
            return{
                uploadUrl:[],
                uploadId:'file',
                uploadCode:0
            };
        },
        watch:{
            uploadCode(val){
                console.info(val)
            }
        }
    };
</script>

后端部分

1.首先安装依赖

npm install ali-oss
npm install co

2.service文件

'use strict'


var OSS = require('ali-oss');
var STS = OSS.STS;
var co = require('co');

var sts = new STS({
    accessKeyId: 'accessKeyId',
    accessKeySecret: 'accessKeySecret',
});
var rolearn = 'acs:ram::ID:role/ram';

var policy = {
    "Version": "1",
    "Statement": [
    {
        "Effect": "Allow",
        "Action": [
        "oss:GetObject",
        "oss:PutObject"
        ],
        "Resource": [
        "acs:oss:*:*:Bucket",
        "acs:oss:*:*:BucketName/*"
        ]
    }
    ]
};

class OssUploadService {

    getOssToken(req, res){
        var result = co(function* () {
            var token = yield sts.assumeRole(rolearn, policy, 15 * 60, 'ossupload');
            res.json({
                token:token.credentials
            })
        }).catch(function (err) {
        });
    }
}

module.exports = new OssUploadService()

2.controller文件

'use strict'
var ossUploadService = require('../service/ossUploadService')
module.exports = function(app) {
  app.get('/alioss/getOssToken', function(req, res) {
    const result = ossUploadService.getOssToken(req, res)
    if (result) {
      res.json({
        code: 100,
        data: result
      })
    }
  })
}

到这里就大功告成了吗?错!这只是完成了最基本的部分,接下来我们要在阿里云控制台中设置权限、角色、策略等。

有时简书不能及时回复,请加我微信或者QQ:2433169657

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我太明显了,简直太明显了。 要偷偷看的人, 我明显地站在人家跟前; 要偷偷想的人, 我明显地对人家表白; 要偷偷爱...
    不得了3阅读 279评论 0 1
  • 优养美丽说阅读 200评论 0 0
  • 山顶祥云气连天 山腰松柏傲冬寒 泉水含羞低声语 山中有我才有仙
    石竹阅读 303评论 17 10
  • 在小学阶段,五年级已经属于高年级。所以我就理所当然的以为五年级的学生已经比较成熟。直到这次见习,才发现自己原来的想...
    偏執l阅读 1,647评论 0 1