1. 程式人生 > >vue 上傳多張圖片到阿里雲

vue 上傳多張圖片到阿里雲

1.引入阿里雲js

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

2.HTML部分 

<div class="uploadImg">
    <h3><i>*</i>上傳圖片:</h3>
    <div class="uploadBox">
        <div class="add-img" v-show="imgList.length">
            <!-- <p class="font14">圖片(最多3張,還可上傳<span v-text="3-imgList.length"></span>張)</p> -->
            <ul class="img-list">
                <li v-for="(url,index) in imgList">
                    <img class="del" src="../../../static/images/publish/blueClose.png" @click.stop="delImg(index)"/>
                    <img :src="url.file.src" class="upImg">
                </li>
            </ul>
        </div>
        <input @change="fileChange($event)" type="file" accept="image/*" id="upload_file" multiple style="display: none"/>
        <div class="add" @click="chooseType" v-if="imgList.length < 3">
            <img src="../../../static/images/brand/uploadPhoto.png">
        </div>
    </div>
</div>

3.css部分

.uploadImg{
    width: 6.9rem;
    height: 2.24rem;
    padding: .3rem .3rem .4rem .3rem;
    h3{
        color: #111;
        font-size: .3rem;
        margin-bottom: .3rem;
    }
    i{
        color: #e65e47;
    }
    .uploadBox{
        .add-img {
            display: inline;
            p {
                color: #999;
            }
        }
        .add {
            display: inline;
            width: 2.2rem;
            height: 1.68rem;
            img{
               width: 2.2rem;
               height: 1.68rem;
            }
        }
        .img-list {
            li {
                float: left;
                text-align: center;
                margin-left: .15rem;
                position: relative;
                width: 2.2rem;
                height: 1.68rem;
                .upImg{
                   width: 2.2rem;
                   height: 1.68rem;
                }
                div{
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 2.2rem;
                    height: 1.68rem;
                    overflow: hidden;
                }
            }
            li:first-child{
                margin-left: 0;
            }
        }

        .del {
            position: absolute;
            width: .38rem;
            height: .38rem;
            top: -.2rem;
            right: -.1rem;
            z-index: 999
        }
    }
}

4.js部分

獲取oss所需引數

ossData(){
    let url = this.changeData() + '/oss/policy'
    axios(url,{
        method: 'post',
        url: url
    }).then(ret => {
        console.log(ret);
        this.host = ret.data.host;
        this.policy = ret.data.policy;
        this.signature = ret.data.signature;
        this.accessid = ret.data.accessid;
        this.dir = ret.data.dir;
        this.expire = ret.data.expire;
        this.callback = ret.data.callback;
    }).catch(err => {
        console.log(err)
    });
},

點選上傳的時候

//上傳圖片
chooseType() {
  document.getElementById('upload_file').click();
},
//點選圖片的時候讓隱藏的input觸發
fileChange(e) {
    //如果發生改變的這個input內容為空直接return,否則新增遍歷這個input-files
    if (!e.target.files[0].size){
      return;
    }else{
      let files = e.target.files;
      //遍歷這個檔案
      for (let i = 0; i < files.length; i++) {
        //判斷是否為資料夾
        if (files[i].type != '') {
          this.fileAdd(files[i]);
        }
      }
    }
},

fileAdd(file) {
    let that = this;
    //如果上傳的沒有超過三張,limit--,如果超過3張,直接return
    if (this.limit !== undefined && this.limit < 0){
      return;
    } else{
      if (this.limit !== undefined){
        this.limit--;
        //判斷是否為圖片檔案
        if (file.type.indexOf('image') == -1) {
          this.$dialog.toast({mes: '請選擇圖片檔案'});
        } else {
          //讀取檔案,成功img標籤可以直接使用的格式
          let reader = new FileReader();
          //開始讀檔案
          reader.readAsDataURL(file);
          //在回撥函式中,才能夠拿到讀取的結果
          reader.onload = function () {
            //把圖片流賦值給當前檔案流的src,新增到陣列中
            file.src = this.result;
            that.imgList.push({file});
          }
        }
      }
    }
},

點選提交的時候

submitbtn(){
  //提交的時候迴圈圖片陣列
  for (var i = 0; i < this.imgList.length; i++) {
    var ossData = new FormData();
    ossData.append('OSSAccessKeyId', this.accessid);
    ossData.append('policy', this.policy);
    ossData.append('Signature', this.signature);
    //上傳阿里的時候需要一個動態的random
    ossData.append('key', this.dir + this.random_string(32));
    ossData.append('success_action_status', 200); // 指定返回的狀態碼
    ossData.append("callback", this.callback);
    ossData.append("file", this.imgList[i].file);
    //提交的時候呼叫阿里雲介面,返回圖片地址
    this.$http.post(this.host, ossData, {
      headers: { "Content-Type": "multipart/form-data" }
    }).then(ret => {
        console.log(ret);
        var arr = "/" + ret.data.fileName;
        this.upImgArr.push(arr);
        this.strImg = this.upImgArr.join(";");
        //呼叫後臺介面把表單資訊傳給後臺
        if(this.imgList.length == this.upImgArr.length){
            let url = this.changeData() + '/project/auth/projectReleased'
            axios(url,{
                method: 'post',
                params: {
                    provinceId: sessionStorage.provinceId, //所在省
                    cityId: sessionStorage.cityId, //所在市
                    projectType: '1',//專案型別1銷售、2招商
                    houseType: 1,//型別1商業、2辦公、3住宅
                    projectPic: this.strImg,//圖片:多張圖使用“;”隔開
                    projectName: "111",//專案名稱
                    price: "3000",//價格
                    acreage: "20",//面積
                    address: "北京",//地址
                    description: "22222",//描述
                }
            }).then(data => {
                console.log(data);
                if(data.data.code == 101){
                  alert("釋出成功")
                }else{
                  alert(data.data.message)
                }
            }).catch(err => {
                console.log(err)
            });
        }
    }).catch(err => {
        console.log(err)
    });
  }
},
random_string(len){
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789';
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
},