vue 上傳圖片到阿里雲(前端直傳:不推薦)

藍天海礁發表於2018-02-05

為何要這樣做:減輕後端資料庫壓力(個人覺得於前端沒啥用,誰返回來都行)


程式碼部分:

    <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都暴露在外面,更安全的方法可見官網的“服務端簽名後上傳”(貌似沒示例)

相關文章