美文网首页
ionic3 上传图片、压缩图片到阿里云 服务端签名后直传

ionic3 上传图片、压缩图片到阿里云 服务端签名后直传

作者: 云小诺 | 来源:发表于2018-06-08 11:26 被阅读0次

1.为什么用plupload.js
首先使用这个plupload是因为我采用的 【阿里云 服务端签名后直传】,使用的是这个方法。
放上阿里云的地址:https://help.aliyun.com/document_detail/31926.html?spm=a2c4g.11174283.6.634.PYDsbd

2.关于plupload.js
大致有以下几个参数:

      runtimes: 'html5,flash,silverlight,html4', // 用来指定上传方式
      browse_button: 'selectfiles', // 触发文件选择对话框的DOM元素
      multi_selection: false, // 是否可以在文件浏览对话框中选择多个文件,true为可以,false为不可以
      container: document.getElementById('container'), // 用来指定Plupload所创建的html结构的父容器
      url: '*******', // 服务器端接收和处理上传文件的脚本地址
      filters: {
        mime_types: [ // 用来限定上传文件的类型
          { title: "Image files", extensions: "jpg,jpeg,gif,png,bmp" },
        ],
        max_file_size: '10mb', // 用来限定上传文件的大小
        prevent_duplicates: true, // 是否允许选取重复的文件,为true时表示不允许,为false时表示允许,默认为false。如果两个文件的文件名和大小都相同,则会被认为是重复的文件
      },
      resize: { // 压缩
        width:1000,
        height:800,
        crop: false,
        quality: 90,
        preserve_headers: false
      },

大致的事件:

Init // 当Plupload初始化完成后触发
PostInit // 当Init事件发生后触发
FilesAdded // 当文件添加到上传队列后触发
BeforeUpload // 当队列中的某一个文件正要开始上传前触发
UploadProgress // 显示上传进度
FileUploaded  // 当队列中的某一个文件上传完成后触发
Error  // 错误

以上是我用到的,大家可以根据自己的需求去添加。具体可参考博客:https://www.cnblogs.com/2050/p/3913184.html
写的很详细了,我也是参考这个博客的,对plupload有了进一步认识。

3.使用
html:

<img class="photo" src="{{photourl}}" alt="">
<div id="ossfile" class="ossfile"></div>
<div id="container" class="upload_btn">
     <button ion-button icon-only id="selectfiles">选择文件</button>
     <button ion-button icon-only id="postfiles">开始上传</button>
</div>

ts:

set_upload_param(up, filename) {
    let token = ********;
    ***********.subscribe((body: any) => {
    // 这里是我向后台发送的请求 获取到需要上传给 阿里云的数据
        let new_multipart_params = {
          'key': dir + '${filename}',
          'policy':policy,
          'OSSAccessKeyId':accessid,
          'success_action_status': '200', //让服务端返回200,不然,默认会返回204
          'signature': signature,
          'x-oss-object-acl': 'public-read'
        };
        up.setOption({
          'url': host,
          'multipart_params': new_multipart_params
        });
        up.start();
      }
    })
  }

  uploadImg() {
  // 这里需要注意 this 的指向问题
    let that = this;
    this.uploader = new plupload.Uploader({
      runtimes: 'html5,flash,silverlight,html4',
      browse_button: 'selectfiles', 
      multi_selection: false, 
      container: document.getElementById('container'), 
      url: '*******', 
      filters: {
        mime_types: [ 
          { title: "Image files", extensions: "jpg,jpeg,gif,png,bmp" },
        ],
        max_file_size: '10mb', 
        prevent_duplicates: true, 
      },
      resize: { 
        crop: false,
        quality: 90,
        preserve_headers: false
      },

      init: {
        PostInit: function () {
          document.getElementById('postfiles').onclick = function () {
            that.set_upload_param(that.uploader, '');
            return false;
          };
        },

        FilesAdded: function (up, files) {
          document.getElementById('ossfile').innerHTML = '';
          plupload.each(files, function (file) {
            document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + '(' + file.name + ')<b></b>'
              + '<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
              + '</div>';
          });

          // 这里【重点】:获取图片的原始尺寸来进行计算 压缩的尺寸
          // 我这里设置的宽1000,高800 
          let image = new Image();
          let reader = new FileReader();
          reader.onload = (readerEvent: any) => {
            image.onload = () => {
              let originalWidth = image.width; // 原始图片的宽
              let originalHeight = image.height; // 原始图片的高
              if (originalWidth >= 1000) {
                that.uploader.settings.resize.width = 1000;
                that.uploader.settings.resize.height = Math.floor(originalHeight * (that.uploader.settings.resize.width / originalWidth));
                if (that.uploader.settings.resize.height > 800) {
                  that.uploader.settings.resize.width = Math.floor(that.uploader.settings.resize.width * (800 / that.uploader.settings.resize.height));
                  that.uploader.settings.resize.height = 800;
                }
              }
              else if (originalHeight > 800) {
                that.uploader.settings.resize.height = 800;
                that.uploader.settings.resize.width = Math.floor(originalWidth * (that.uploader.settings.resize.height / originalHeight));
              }
              else {
                that.uploader.settings.resize.width = originalWidth;
                that.uploader.settings.resize.height = originalHeight;
              }
            };
            image.src = readerEvent.target.result;
          };
          reader.readAsDataURL(files[0].getNative());
        },

        BeforeUpload: function (up, file) {
          that.set_upload_param(up, file.name);
        },

        UploadProgress: function (up, file) {
          var d = document.getElementById(file.id);
          d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
          var prog = d.getElementsByTagName('div')[0];
          var progBar = prog.getElementsByTagName('div')[0]
          progBar.style.width = 2 * file.percent + 'px';
          progBar.setAttribute('aria-valuenow', file.percent);
        },

        FileUploaded: function (up, file, info) {
          if (info.status == 200) {
            that.appStatus.infoMsg('上传成功');
            // 这一步是 上传成功后,清除进度条
            document.getElementById('ossfile').innerHTML = '';
          }
          else if (info.status == 203) {
            console.log('上传到OSS成功,但是oss访问用户设置的上传回调服务器失败');
            console.log('失败原因是:' + info.response);
          }
          else {
            console.log('失败原因是:' + info.response);
          }
        },

        Error: function (up, err) {
          if (err.code == -600) {
            that.appStatus.infoMsg("选择的文件太大了!")
          }
          else if (err.code == -601) {
            that.appStatus.infoMsg("选择的上传文件类型不对!")
          }
          else if (err.code == -602) {
            that.appStatus.infoMsg("这个文件已经选择过一遍了!")
          }
          else {
            console.log(err.response)
          }
        }
      }
    });
    this.uploader.init();
  }

【重点】:

  1. this的指向问题
  2. resize的宽高动态赋值需要是:uploader.settings.resize.width 、uploader.settings.resize.height
  3. resize只给宽,比如
    resize: {
    width:800,
    crop: false,
    quality: 90,
    preserve_headers: false
    },
    这个能实现压缩,图片体积可以压缩,宽高可以不进行剪裁 同比例缩小。图片大于800进行压缩,小于不压缩。我的需求是限定了高,所以要进行计算。
  4. 案例上的进度条是 同时存在多个。我的需求是 只显示一个,成功后消失。具体代码是:
FilesAdded: function (up, files) {
          document.getElementById('ossfile').innerHTML = '';
          plupload.each(files, function (file) {
            document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + '(' + file.name + ')<b></b>'
              + '<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
              + '</div>';
          });
}

FileUploaded: function (up, file, info) {
          if (info.status == 200) {
            that.appStatus.infoMsg('上传成功');
            // 这一步是 上传成功后,清除进度条
            document.getElementById('ossfile').innerHTML = '';
          }
}

这个实现了我的需求,还有许多不足之处,大家可以做个参考!

最后给大家看下我的页面效果:


image.png

相关文章

网友评论

      本文标题:ionic3 上传图片、压缩图片到阿里云 服务端签名后直传

      本文链接:https://www.haomeiwen.com/subject/wmiwsftx.html