vue element+oss上传文件

# 1.引入oss

npm i ali-oss -D

## 2.新建aliyun.oss.client.js

```js

/*

* 阿里云oss上传工具

*

* @description conf: {

                region: null,

                accessKeyId: null,

                accessKeySecret: null,

                bucket: null,

                stsToken: null

            }

*/

import OSS from 'ali-oss';

export default (conf) => {

    return new OSS(conf);

};

```

3.在需要使用的文件,例如about.vue

```js

<template>

  <div class="about">

    <el-button type="success" @click="init">获取上传信息</el-button>

    <el-upload

      class="avatar-uploader"

      action=""

      :show-file-list="false"

      drag

      :multiple="false"

      :http-request="uploadHttp"

      list-type="picture"

    >

      <div class="el-upload__text">

        <el-button type="warning">点击上传</el-button>

      </div>

    </el-upload>

    <img class="ossimg" :src="avatar" alt="" />

  </div>

</template>

<script>

import ossClient from "@/assets/js/aliyun.oss.client";

export default {

  data() {

    return {

      uploadConf: {

        region: null,

        accessKeyId: null,

        accessKeySecret: null,

        bucket: null,

        stsToken: null,

      },

      avatar: "",

    };

  },

  methods: {

    init() {

      this.$api

        .getOssAuth()  //通过请求接口获取上传信息

        .then((res) => {

          if (res.data.success) {

            this.uploadConf.region = "oss-cn-beijing";

            this.uploadConf.accessKeyId = res.data.data.accessKeyId;

            this.uploadConf.accessKeySecret = res.data.data.accessKeySecret;

            this.uploadConf.bucket = res.data.data.bucket;

            this.uploadConf.stsToken = res.data.data.securityToken;

            this.uploadConf.defaultPath = res.data.data.defaultPath;

          }

        })

        .catch((err) => {

          console.log(err);

        });

    },

    // 阿里云OSS上传

    uploadHttp({ file }) {

      const imgName = this.uploadConf.defaultPath;

      const fileName = `${imgName}/${Date.parse(new Date())}`; //定义唯一的文件名

      ossClient(this.uploadConf)

        .put(fileName, file, {

          ContentType: "image/jpeg",

        })

        .then(({ res, url, name }) => {

          if (res && res.status == 200) {

            console.log(`上传图片成功`, res, url, name);

            this.avatar = url;  //上传成功后返回的文件路径

          }

        })

        .catch((err) => {

          console.log(`上传图片失败`, err);

        });

    },

  },

};

</script>

<style scoped lang="stylus">

.about {

  text-align center

}

.ossimg {

  max-width 500px

}

.avatar-uploader {

  width 125px

  height 45px

}

>>>.avatar-uploader .el-upload {

  width 125px

  height 45px

  border-radius 6px

  cursor pointer

  position relative

  overflow hidden

}

.el-upload__text {

  width 125px

  height 45px

}

</style>

```

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

推荐阅读更多精彩内容