网络编程 
首页 > 网络编程 > 浏览文章

Vue移动端实现图片上传及超过1M压缩上传

(编辑:jimmy 日期: 2024/5/20 浏览:3 次 )

本文实例为大家分享了Vue移动端实现图片上传及超过1M压缩上传的具体代码,供大家参考,具体内容如下

1、实现效果

Vue移动端实现图片上传及超过1M压缩上传

2、代码

Html:

<div class="choosePic">
  <div class="pics" :style="{backgroundImage: 'url(' + form.erpRecords + ')'}">
   <input type="file" class="uploads" @change="uploadserpRecords" accept="image/*" multiple >
   <img src="/UploadFiles/2021-04-02/ic_AddImage@3x.png">

Css:使用了less ,需要引入less,才能使用(npm install less less-loader --save)

.choosePic{
  margin: 0.64rem 0;
  .pics{
  background-position: center;
  background-size: cover;
  width: 15.1467rem;
  height: 5.5467rem;
  background-color: #F9F9F9;
  border: 2px solid #C3C3C3;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1rem;
  color: #3DCA9A;
  font-weight: bold;
  border-radius: 0.213rem;
  >div{
   margin-left: 0.213rem;
   letter-spacing: 2px
  }
  .uploads{
   position: absolute;
   z-index: 99;
   left: 0;
   width: 99%;
   height: 5.5467rem;
   opacity: 0;
  }
  img{
   width: 1.4933rem;
   height: 1.4933rem;
  }

  }
 }

JS:

/**
 * 上传销售记录
 */
uploadserpRecords (e) {
 let file = e.target.files[0]
 if (file === undefined) {
 return
 }
 if (file.size / 1024 > 1025) { // 文件大于1M(根据需求更改),进行压缩上传
 that.photoCompress(file, { // 调用压缩图片方法
  quality: 0.2
 }, function (base64Codes) {
  // console.log("压缩后:" + base.length / 1024 + " " + base);
  let bl = that.base64UrlToBlob(base64Codes)
  // file.append('file', bl, 'file_' + Date.parse(new Date()) + '.jpg') // 文件对象
  that.uploadLice(bl) // 请求图片上传接口
 })
 } else { // 小于等于1M 原图上传
 this.uploadLice(file)
 }
}, 
/**
 * base64 转 Blob 格式 和file格式
 */
base64UrlToBlob (urlData) {
 let arr = urlData.split(','),
 mime = arr[0].match(/:(.*"_blank" href="//www.jb51.net/Special/926.htm">vue.js组件学习教程进行学习。

更多vue学习教程请阅读专题《vue实战教程》

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:vue项目实现图片上传功能
下一篇:vue图片上传组件使用详解