首页 > 其他分享 >element Compressor图片压缩且上传-

element Compressor图片压缩且上传-

时间:2023-04-07 15:34:57浏览次数:28  
标签:return res data Compressor else file uploadType element 上传

 

 上传了压缩后的照片

 

<template>
  <div>
    <!-- <el-upload :class="uploadDisabled" ref="upload" :action="action" :headers="headers" list-type="picture-card"
      :limit="1" :file-list="fileList" :on-exceed="handleExceed" :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove" :on-success="handleSuccess" :before-upload="beforeUpload" :http-request="customUpload">
      <i class="el-icon-plus"></i>
    </el-upload> -->
    <el-upload :class="uploadDisabled" ref="upload" :action="action" :headers="headers" list-type="picture-card"
      :limit="1" :file-list="fileList" :on-exceed="handleExceed" :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove" :before-upload="beforeUpload" :http-request="customUpload">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { uploadImage } from '@/api/homeApi';
import Compressor from "compressorjs";
export default {
  props: {
    upImg: {
      type: String,
      default: () => {
        return "";
      },
    },
    uploadType: {
      type: String,
      default: () => {
        return "";
      },
    },
  },
  data() {
    return {
      action: this.$store.state.app.actionUrl,
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      uploadDisabled: "",
      attachmentId: [],
      headers: {
        "author-token-key": localStorage.getItem("token"),
      },
    };
  },
  created() {
    this.fileList = this.upImg ? [{ url: this.upImg }] : [];
    console.log("action", this.action);
  },
  watch: {
    upImg: {
      handler(newData, oldData) {
        this.fileList = newData ? [{ url: newData }] : [];
        if (this.fileList.length > 0) {
          this.uploadDisabled = "disabled";
        } else {
          this.uploadDisabled = "";
        }
      },
      deep: true,
    },
  },
  methods: {
    handleRemove(file, fileList) {
      this.attachmentId = [];
      if (this.uploadType == "front") {
        this.$emit("getFrontImg", "");
      } else if (this.uploadType == "verso") {
        this.$emit("getVersoImg", "");
      } else if (this.uploadType == "enteerprise") {
        this.$emit("getEnterpriseImg", "");
      }
      this.uploadDisabled = "";
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(res, file) {
      console.log(res, file, '成功')
      // this.attachmentId.push(res);
      // if (this.attachmentId.length > 0) {
      //   this.uploadDisabled = "disabled";
      // }
      // if (this.uploadType == "front") {
      //   this.$emit("getFrontImg", res.data);
      // } else if (this.uploadType == "verso") {
      //   this.$emit("getVersoImg", res.data);
      // } else if (this.uploadType == "enteerprise") {
      //   this.$emit("getEnterpriseImg", res.data);
      // }
    },
    beforeUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/JPEG/PNG 格式!");
        return false
      }
      if (!isLt5M) {
        this.$message.error("上传图片大小不能超过 5MB!");
        return false
      }
      // return isJPG && isLt5M;
      //=====
      const image = new Image();
      image.src = URL.createObjectURL(file);
      let fileSize = file.size; //照片尺寸大小
      let imgsize = fileSize / 1024;
      if (imgsize < 10) {
        this.$message.error("上传图片大小不能小于10kb");
        return false
      } else if (imgsize < 200) {
        console.log("图片不超过200k不压缩,直接上传")
      } else if (fileSize < 5 * 1024 * 1024) {
        console.log('需要压缩')
        this.customUploadys(file)
        return false
      } else {
        this.$message.error("超出允许的文件大小");
        return false
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能上传一张图片");
      return false
    },
    //手动上传
    customUpload(file) {
      const formdd = new FormData();
      // 文件对象
      formdd.append("file", file.file);
      uploadImage(formdd).then(res => {
        this.attachmentId.push(res.data);
        if (this.attachmentId.length > 0) {
          this.uploadDisabled = "disabled";
        }
        if (this.uploadType == "front") {
          this.$emit("getFrontImg", res.data.data);
        } else if (this.uploadType == "verso") {
          this.$emit("getVersoImg", res.data.data);
        } else if (this.uploadType == "enteerprise") {
          this.$emit("getEnterpriseImg", res.data.data);
        }
      })
    },
    customUploadys(file) {
      let _this = this;
      new Compressor(file, {
        quality: 0.6,
        width: 380,
        success(result) {
          let blob = new Blob([result], {
            type: 'image/jpeg'
          })
          let url = window.URL.createObjectURL(blob)
          // 构建FormData
          let formData = new FormData();
          //注意:此处第3个参数最好传入一个带后缀名的文件名,否则很有可能被后台认为不是有效的图片文件
          formData.append("file", blob, file.name);
          uploadImage(formData).then(res => {
            _this.attachmentId.push(res.data);
            if (_this.attachmentId.length > 0) {
              _this.uploadDisabled = "disabled";
            }
            if (_this.uploadType == "front") {
              _this.$emit("getFrontImg", res.data.data);
            } else if (_this.uploadType == "verso") {
              _this.$emit("getVersoImg", res.data.data);
            } else if (_this.uploadType == "enteerprise") {
              _this.$emit("getEnterpriseImg", res.data.data);
            }
          })
        },
        error(err) {
          console.log(err.message);
          return false
        },
      })
    }
  },
};
</script>

<style lang="less">
.disabled .el-upload--picture-card {
  display: none;
}
</style>
export function uploadImage(data) {
  return util.http({
    url: `/sdfs/file/uploadImage`,
    method: 'post',
    // headers: { "content-type": "multipart/form-data" },
    data
  })
}

 

标签:return,res,data,Compressor,else,file,uploadType,element,上传
From: https://www.cnblogs.com/Byme/p/17296313.html

相关文章

  • PHPCMS粘贴图片自动上传到服务器(Java版)
    ​ 这种方法是servlet,编写好在web.xml里配置servlet-class和servlet-mapping即可使用后台(服务端)java服务代码:(上传至ROOT/lqxcPics文件夹下)<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@     page contentType="text/html;cha......
  • 文件的上传与下载
    1、文件上传下载1.1文件上传什么是文件上传?要将客户端(浏览器)大数据存储到服务器端,不将数据直接存储到数据库中,而是要将数据存储到服务器所在的磁盘上,这就要使用文件上传。为什么使用文件上传?通过文件上传,可以将浏览器端的大数据直接保存到服务器端。不将数据保存到数据库中,......
  • 织梦CMS粘贴图片自动上传到服务器(Java版)
    ​如何做到ueditor批量上传word图片?1、前端引用代码<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>......
  • easy excel 分页查询数据并上传文件服务器返回链接
    背景之前看到公司的excel下载是先分页查询再上传到obs(华为云服务器),最后返回链接的,最近在学习easyexcel特意记录一下。目的实现easyexcel分页查询数据并上传文件服务器返回链接参考链接这里实现代码点击查看代码@GetMapping("downloadOssUrl")@ResponseBody......
  • 动易CMS粘贴图片自动上传到服务器(Java版)
    ​ 自动导入Word图片,或者粘贴Word内容时自动上传所有的图片,并且最终保留Word样式,这应该是Web编辑器里面最基本的一个需求功能了。一般情况下我们将Word内容粘贴到Web编辑器(富文本编辑器)中时,编辑器都无法自动上传图片。需要用户手动一张张上传Word图片。如果只有一张图片还能够接......
  • .net core文件上传与下载
    使用Asp.NetCore进行文件的上传与下载控制器代码如下usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Threadi......
  • 解决微信小程序主包过大,无法上传代码问题
    1、我的开发工具是HBuilderX,所以,在运行小程序的时候可以勾选运行>运行到模拟器>运行时是否压缩代码,   小程序运行时,这里会提示2、所以,可以选择发行>小程序-微信,注意括号的内容,只适用于uni-app   3、另外,在package.json文件里面加入 --minimize最小压缩 "dev:m......
  • Springboot+HTML5+Layui2.7.6上传文件【请求上传接口出现异常】
    1.最近两天在springboot+html5项目中发现在用layui框架时报请求上传接口出现异常这个错误。2.将代码全部整理了一遍,发现前端后台都没错!!!但是还是【请求上传接口出现异常】,于是跑去翻看layui官网。 3.最终最终将错误锁定到了返回的JSON字符串中,我是返回的String,所以一直都会......
  • c#.net怎么实现web端上传超大文件
    ​ASP.NET上传文件用FileUpLoad就可以,但是对文件夹的操作却不能用FileUpLoad来实现。下面这个示例便是使用ASP.NET来实现上传文件夹并对文件夹进行压缩以及解压。ASP.NET页面设计:TextBox和Button按钮。​编辑TextBox中需要自己受到输入文件夹的路径(包含文件夹),通过Button实......
  • element-plus中Container 布局容器左右留白
    index.vue代码如下:<scriptlang="ts"setup></script><template><el-containerclass="layout"><el-asideclass="aside"width="200px">Aside</el-aside><el-contain......