vuejs2.0 上傳圖片到七牛雲項目實戰----權威獨一份

最近在使用 vue2.0開發網頁 其中涉及到 選擇圖片的操做,故整理了以下實例vue


安裝

npm install --save jquery

main.js======引用======import $ from 'jquery'

<div class="logo">
            <div class="upload-container">
                <div class="imgBox">
                    <input type="file" class="inputstyle" name="file" @change="PreviewImage"  />
                    <img :src="imageUrl" alt="" class="fileImg">
                </div>
            </div>
        </div>

mounted(){
//          初始化token
        this.http.get('/qiniu-token')
            .then(res =>{
                this.qiniutoke=res.data.token;
                console.log('------')
                console.log(res.data.token)
            })
            .catch(function (error) {
                console.log(error);
            });
          this.shuaxin();
        },

methods: {
//            上傳頭像
            PreviewImage(event){
                this.http.get('/qiniu-token')
                    .then(res =>{
                        this.qiniutoke=res.data.token;
                        console.log('------')
                        console.log(res.data.token)
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
                var addr = 'http://opf2ucy0n.bkt.clouddn.com/'
                var file = event.target.files[0];
                var formData = new FormData();
                formData.append('file', file);
                formData.append('token', this.qiniutoke);
                $.ajax({
                    url: 'http://up-z1.qiniu.com/',
                    type: 'POST',
                    dataType: 'json',
                    cache: false,
                    data: formData,
                    processData: false,
                    contentType: false
                }).done((res) => {
                    this.imageUrl= addr+res.key
                }).fail(function(err) {
                    console.log('error');
                });

            },
          }

總結:
token每家公司都不同
若是從後臺調取接口,token必須每次都不同
addr 變量爲圖片路徑前綴

七牛官方文檔jquery

相關文章
相關標籤/搜索