vue.js + axios.js图片压缩处理并上传到服务器demo

2022-06-09 11:22:18 浏览数 (1)

点击查看效果

图片压缩原理

将图片重新画入一个canvas中。可设置最大宽度,再按图片宽高比例定义canvas画布的宽高。

完整代码demo

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
    <meta name="renderer" content="webkit">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>

    <link rel="stylesheet" href="css/upload-img.css">
</head>
<body>
<div id="app" class="container" v-cloak>
    <div class="uploading-data" v-if="isUploading"></div>

    <div class="upload-img-column">
        <div class="words">上传图片 ({{imgTempList.length}}/5)</div>
        <div class="upload-wrap">
            <div class="box">
                <label class="p dotted">
                    <input type="file" accept="image/jpg,image/jpeg,image/png" name="file"
                           @change="onChooseImage($event)"/>
                    <img src="./img/jiahao.png" alt="">
                </label>
            </div>
            <template v-for="(imgItem, imgIndex) in imgTempList">
                <div class="box">
                    <div class="p">
                        <img :src="imgItem">
                        <div class="delete" @click.stop="deleteImg(imgIndex)">
                            <img src="./img/guanbi.png" alt="">
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <button class="l-btn" @click="onUploadImg">上传</button>

    <!-- 图片上传成功后返回的路径(没必要的) -->
    <div class="success-path">
        <template v-for="(item, index) in successPath">
            <a :href="item" target="_blank">{{item}}</a>
        </template>
    </div>

</div>

<script src="js/vue-2.5.21.js"></script>
<script src="js/axios.js"></script>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            imgTempList: [], //图片临时路径列表
            isUploading: false, //是否正在上传
            successPath: [], //上传成功后的路径(没必要)
        },
        mounted: function () {
            var that = this;
        },
        watch: {},
        methods: {
            //选择图片
            onChooseImage: function (event) {
                var that = this;

                //判断图片数量是否已上限
                var currentImgTempArray = that.imgTempList;
                if (currentImgTempArray.length >= 5) {
                    alert("最多上传5张图片");
                    return false;
                }

                //使用FileReader对文件对象进行操作
                var reader = new FileReader();
                reader.readAsDataURL(event.target.files[0]); //将读取到的文件编码成Data URL
                reader.onload = function () { //读取完成时
                    var replaceSrc = reader.result; //文件输出的内容


                    //调用图片压缩处理方法
                    that.compressedImage({
                        src: replaceSrc,
                        quality: 0.8,
                        success: function (src) {
                            //将压缩后的路径 追加到临时路径数组中
                            var totalList = [];
                            if (currentImgTempArray.length > 0) {
                                totalList = currentImgTempArray.concat(src);
                            } else {
                                totalList[0] = src;
                            }
                            that.imgTempList = totalList;
                        }
                    });
                };

            },

            //删除某张图片
            deleteImg: function (idx) {
                var that = this;
                that.imgTempList.splice(idx, 1);
            },


            //提交上传图片
            onUploadImg: function () {
                var that = this;
                var imgTempList = that.imgTempList;
                if (imgTempList.length > 0) {

                    that.isUploading = true; //正在上传 显示遮罩层 防止连续点击

                    var countNum = 0; //计算数量用的 判断上传到第几张图片了

                    //map循环遍历上传图片
                    imgTempList.map(function (imgItem, imgIndex) {
                        var files = that.dataURLtoFile(imgItem, 'pj'   Date.now()   '.jpg'); //DataURL转File

                        //创FormData对象
                        var formdata = new FormData();
                        //append(key,value)在数据末尾追加数据。 这儿的key值需要和后台定义保持一致
                        formdata.append('img', files);

                        //用axios上传,
                        axios({
                            method: "POST",
                            url: "http://www.clluo.com:8060/uploadImg",
                            data: formdata,
                            headers: {
                                "Content-Type": "multipart/form-data"
                            }
                        }).then(function (res) {
                            countNum  ;
                            //图片全部上传完后去掉遮罩层
                            if (countNum >= imgTempList.length) {
                                that.isUploading = false;
                            }

                            //没必要的代码 


	

0 人点赞