vue上傳圖片壓縮

<template>
<div class="upload">
    <div class="uploadHead">
        <div class="uploadHeadTop">出倉單號(hào)</div>
        <div class="uploadHeadBottom">LCGT20210822026</div>
    </div>
    <div class="uploadTips">
        <div class="uploadTipsTop">
            <div class="uploadTipsTit">目的地</div>
            <div class="uploadTipsMsg">高明美宗</div>
        </div>
        <div class="uploadTipsBottom">
            <div class="uploadTipsTit">車牌號(hào)</div>
            <div class="uploadTipsMsg">粵X32659</div>
        </div>
    </div>
    <div>
        <div class="uploadBtnBox">
            <van-uploader :after-read="afterRead">
                <div class="uploadBtn">
                    <div class="uploadBtnL">點(diǎn)此上傳磅單</div>
                    <div class="uploadBtnR">
                        <img src="@/assets/uploadimg.png" alt="">
                    </div>
                </div>
            </van-uploader>
        </div>
        <div class="uploadBtnTips">
            *該單據(jù)已上傳過磅單 如有要您可繼續(xù)上傳
        </div>
    </div>
    
    <!-- <div class="uploadOK">出倉單已送達(dá),無法上傳磅單</div> -->
</div>
</template>
<script>
import { ref ,reactive,getCurrentInstance,onMounted} from 'vue';
export default{
    setup() {
        
    },
    data() {
      return {

      };
    },
    mounted() {
        
    },
    computed: {
      
    },
    methods:{
        uploadImg(blob, base64) {
            const formData = new FormData();
            formData.append("attach", blob, ".jpg");
            this.$http.postImg(this.$api.UPLOAD, formData).then((res) => {
                // if (res.code == 0) {
                // let obj = {};
                // obj["src"] = res.data;
                // this.picList.push(obj);
                // console.log(this.picList);
                // }
                console.log(res)
            });
        },
        blobToBase64(blob) {
            const self = this; // 綁定this
            const reader = new FileReader();
            reader.readAsDataURL(blob); // 添加二進(jìn)制文件
            reader.onload = function (event) {
                const base64 = event.target.result; // 獲取到它的base64文件
                const scale = 0.5; // 設(shè)置縮放比例 (0-1)
                self.compressImg(base64, scale, self.uploadImg);
            };
        },
        compressImg(base64, scale, callback) {
            console.log(`執(zhí)行縮放程序卿拴,scale=${scale}`);
            const img = new Image();
            img.src = base64;
            img.onload = function () {
                const canvas = document.createElement("canvas");
                const ctx = canvas.getContext("2d");
                canvas.setAttribute("width", this.width);
                canvas.setAttribute("height", this.height);
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                let base64 = canvas.toDataURL("image/jpeg");
                while (base64.length > 1024 * 1024 * 3) {
                scale -= 0.01;
                base64 = canvas.toDataURL("image/jpeg", scale);
                }
                const arr = base64.split(",");
                const mime = arr[0].match(/:(.*?);/)[1];
                const bytes = atob(arr[1]);
                const bytesLength = bytes.length;
                const u8arr = new Uint8Array(bytesLength);
                for (let i = 0; i < bytes.length; i++) {
                u8arr[i] = bytes.charCodeAt(i);
                }
                const blob = new Blob([u8arr], { type: mime });
                callback(blob, base64);
            };
        },
        afterRead(files) {
            console.log(files.file)
            // let files = e.target.files;
            this.blobToBase64(files.file);
        },
    }
}
</script>
<style scoped>
.uploadHead{
    width: 622px;
    height: 164px;
    background: #f3f4f5;
    margin: 0 auto;
    margin-top: 40px;
    text-align: center;
}
.uploadHeadTop{
    font-size: 28px;
    color: #999999;
    padding-bottom: 8px;
    padding-top: 32px;
}
.uploadHeadBottom{
    color: #333333;
    font-size: 40px;
}
.uploadTips{
    display: flex;
    padding: 0 64px;
    margin-top: 64px;
    margin-bottom: 120px;
}
.uploadTipsTop{
    width: 50%;
    text-align: center;
}
.uploadTipsBottom{
    width: 50%;
    text-align: center;
}
.uploadTipsTit{
    font-size: 28px;
    margin-bottom: 8px;
    color: #999999;
}
.uploadTipsMsg{
    font-size: 34px;
    color: #333333;
}
.uploadBtnBox{
    display: flex;
    margin: 0 64px;
}
.uploadBtn{
    background: #1F7DE9;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 16px;
    width: 622px;
    padding: 64px 64px;
    box-sizing: border-box;
}
.uploadBtnR img{
    width: 174px;
}
.uploadBtnL{
    font-size: 34px;
    color: #fff;
}
.uploadOK{
    color: #d80f09; 
    font-size: 40px;
    text-align: center;
    padding-top: 60px;
}
.uploadBtnTips{
    width: 324px;
    height: 96px;
    font-size: 34px;
    color: #d80f09;
    text-align: center;
    margin: 0 auto;
    margin-top: 40px;
}

</style>

import axios from "axios";
import QS from 'qs';
import config from "../../config";

axios.defaults.baseURL = config.API_URI;

axios.defaults.timeout = 10000;

axios.defaults.withCredentials = true;


axios.interceptors.request.use(
    config => {
        //請(qǐng)求之前(可以設(shè)置token)
        // if (localStorage.getItem('token')){  // 判斷是否存在token,如果存在的話乾吻,則每個(gè)http header都加上token
        //  config.headers.common['Token'] = localStorage.getItem('token') || ''
        // }
        return config;
    },
    error => {
        alert(error);
        return Promise.reject(error);
    }
);


 axios.interceptors.response.use(
     response => {
        //數(shù)據(jù)拿到之后
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
    error => {
        alert("Http請(qǐng)求失敗燃观,請(qǐng)聯(lián)系管理員");
        return Promise.reject(error.response);
    }
);

//成功方法
function successfun(res) {
    //處理后臺(tái)返回的非200錯(cuò)誤
    if (res.code === 0) {
        return res;
    } else {
        alert(res.msg);
        return res;
    }
}

//錯(cuò)誤方法
function errorfun(res) {
    if (res.code != 1) {
        alert(res.msg);
        return res;
    }
}

export default {
    postImg(url, data) {
        //post請(qǐng)求
        return axios({
            method: "post",
            url,
            data: data,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(
            res => {
                return successfun(res.data);
            },
            err => {
                return errorfun(err);
            }
        );
    },
    post(url, data) {
        //post請(qǐng)求
        return axios({
            method: "post",
            url,
            data: QS.stringify(data),
        }).then(
            res => {
                return successfun(res.data);
            },
            err => {
                return errorfun(err);
            }
        );
    },
    get(url, params) {
        //get請(qǐng)求
        return axios({
            method: "get",
            url,
            params,
        }).then(
            res => {
                return successfun(res.data);
            },
            err => {
                return errorfun(err);
            }
        );
    }
};

第一個(gè)文件,afterRead方法是vant框架的上傳獲取原生文件流
第二個(gè)文件追他,設(shè)置多一個(gè)方法postImg坟募,設(shè)置headers

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市邑狸,隨后出現(xiàn)的幾起案子懈糯,更是在濱河造成了極大的恐慌,老刑警劉巖单雾,帶你破解...
    沈念sama閱讀 211,265評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赚哗,死亡現(xiàn)場離奇詭異,居然都是意外死亡铁坎,警方通過查閱死者的電腦和手機(jī)蜂奸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,078評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來硬萍,“玉大人扩所,你說我怎么就攤上這事∑庸裕” “怎么了祖屏?”我有些...
    開封第一講書人閱讀 156,852評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長买羞。 經(jīng)常有香客問我袁勺,道長,這世上最難降的妖魔是什么畜普? 我笑而不...
    開封第一講書人閱讀 56,408評(píng)論 1 283
  • 正文 為了忘掉前任期丰,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘钝荡。我一直安慰自己街立,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,445評(píng)論 5 384
  • 文/花漫 我一把揭開白布埠通。 她就那樣靜靜地躺著赎离,像睡著了一般。 火紅的嫁衣襯著肌膚如雪端辱。 梳的紋絲不亂的頭發(fā)上梁剔,一...
    開封第一講書人閱讀 49,772評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音舞蔽,去河邊找鬼荣病。 笑死,一個(gè)胖子當(dāng)著我的面吹牛渗柿,可吹牛的內(nèi)容都是我干的众雷。 我是一名探鬼主播,決...
    沈念sama閱讀 38,921評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼做祝,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼砾省!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起混槐,我...
    開封第一講書人閱讀 37,688評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤编兄,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后声登,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體狠鸳,經(jīng)...
    沈念sama閱讀 44,130評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,467評(píng)論 2 325
  • 正文 我和宋清朗相戀三年悯嗓,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了件舵。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,617評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡脯厨,死狀恐怖铅祸,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情合武,我是刑警寧澤临梗,帶...
    沈念sama閱讀 34,276評(píng)論 4 329
  • 正文 年R本政府宣布,位于F島的核電站稼跳,受9級(jí)特大地震影響盟庞,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜汤善,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,882評(píng)論 3 312
  • 文/蒙蒙 一什猖、第九天 我趴在偏房一處隱蔽的房頂上張望票彪。 院中可真熱鬧,春花似錦不狮、人聲如沸抹镊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,740評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至颈渊,卻和暖如春遂黍,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背俊嗽。 一陣腳步聲響...
    開封第一講書人閱讀 31,967評(píng)論 1 265
  • 我被黑心中介騙來泰國打工雾家, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人绍豁。 一個(gè)月前我還...
    沈念sama閱讀 46,315評(píng)論 2 360
  • 正文 我出身青樓芯咧,卻偏偏與公主長得像,于是被迫代替她去往敵國和親竹揍。 傳聞我的和親對(duì)象是個(gè)殘疾皇子敬飒,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,486評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容