javascript - 通过调整 dropzone.js 压缩图像

标签 javascript jquery html image dropzone.js

我是 JS 的新手,最近几天我一直在客户端压缩图像。我想要做的是,用户将一堆图像(可以超过 10 张)放在 dropzone 中,应该使用 JIC 对其进行压缩。一旦用户点击一个按钮上传所有压缩文件就会上传到服务器。

到目前为止,我的代码只能在删除一张图片时压缩和上传,但是当我删除多张图片时,所有图片都保持未压缩状态,只有一张。我不确定我做错了什么。我尝试遵循 this post 中的解决方案但无法实现我的目标。我使用的代码如下:

Dropzone.autoDiscover=false;
var myDropZone=new Dropzone("#dropzonePreview",{
      url:"/dragdrop",
      autoProcessQueue:false,
      acceptedFiles: 'image/*',
      parallelUploads: 10,

      init:function(){
        this.on('addedfile', function(file){

            _this = this;
            ////console.log("Added File");
            $('#userphoto').css('color', "transparent");
            EXIF.getData(file, function(){ // async call
              var lat=EXIF.getTag(this,"GPSLatitude");
              var lon=EXIF.getTag(this,"GPSLongitude");
              geocoder.geocode( { 'latLng': temp }, function(results, status) { // another async call });
              }
            });

            myReader2 = new FileReader(); // Reading image for compression purpose
            myReader2.onload = function(event) {
                console.log(file.status);
                // var i = new Image();

                var i = document.getElementById("source_image");
                i.src = event.target.result;

                i.onload = function() {
                  var source_image = document.getElementById('source_image');

                  var quality = 70;

                  comp = jic.compress(source_image, 70, "jpg"); // Link to function can be found at the end of code.

                  var editedFile = base64ToFile(comp.src, file); // same function used in mentioned stackoverflow post.

                    // Replace original with resized

                    var origFileIndex = myDropZone.files.indexOf(file);
                    myDropZone.files[origFileIndex] = editedFile;

                    editedFile.status = Dropzone.ADDED;
                    myDropZone.enqueueFile(editedFile);

                    delete source_image;
                };
            };
            myReader2.readAsDataURL(file);
        });

        this.on("sending",function(file,xhr,formData){
          //appending some data to formData
        });

        this.on("complete", function(file){
            // processing like removing objects of file from drop zone
        });
      }
    });

$('#upload').click(function(evt){ // Button that triggers uploading file 
      myDropZone.processQueue();
}

链接到 function .非常感谢您的帮助。谢谢。

最佳答案

我已经找到了这个问题的解决方案。这对我有用。

请检查

function base64ToFile(dataURI, origFile) {
  var byteString, mimestring;

  if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
    byteString = atob(dataURI.split(',')[1]);
  } else {
    byteString = decodeURI(dataURI.split(',')[1]);
  }

  mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0];

  var content = new Array();
  for (var i = 0; i < byteString.length; i++) {
    content[i] = byteString.charCodeAt(i);
  }

  var newFile = new File(
    [new Uint8Array(content)], origFile.name, {type: mimestring}
  );


  // Copy props set by the dropzone in the original file

  var origProps = [ 
    "upload", "status", "previewElement", "previewTemplate", "accepted" 
  ];

  $.each(origProps, function(i, p) {
    newFile[p] = origFile[p];
  });

  return newFile;
}
Dropzone.autoDiscover = false;
jQuery(document).ready(function($) {

var myDropZone=new Dropzone("#dropzonePreview",{
     url:"/dragdrop",
     autoProcessQueue:false,
     acceptedFiles: 'image/*',
     parallelUploads: 10,

      init:function(){

        this.on("sending",function(file,xhr,formData){

        });
        this.on("complete", function(file){

        });
      }

     });
myDropZone.on("addedfile", function(file) {

        var reader = new FileReader();

        reader.addEventListener("load", function(event) {

          var origImg = new Image();
          origImg.src = event.target.result;

          origImg.addEventListener("load", function(event) { 
            comp = jic.compress(origImg, 30, "jpg");  
            var resizedFile = base64ToFile(comp.src, file);
            var origFileIndex = myDropZone.files.indexOf(file);
            myDropZone.files[origFileIndex] = resizedFile;
            myDropZone.enqueueFile(resizedFile);
          });
        });
        reader.readAsDataURL(file);
      });
$('#upload').click(function(e){ // Button that triggers uploading file 
    e.preventDefault();
    myDropZone.processQueue();  
});

});

关于javascript - 通过调整 dropzone.js 压缩图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41419031/

相关文章:

javascript - 如何仅在平板电脑/手机上将主 slider 的布局从 'partialview' 更改为 'fillwidth'

javascript - 在所有现代浏览器上检测缩放级别

javascript - jQuery-onclick : Why does it execute click right on adding handler?

jquery - SPA Durandal 应用程序 : how can i reload current page in router

javascript - 更改现有的 css 属性并通过删除或添加 css 元素来使用它

javascript - 如何模糊 Canvas 元素的一部分?

html - 如何避免默认的 -webkit 属性

javascript - 在 jQuery 中切换 wordpress 中的事件和非事件 div

javascript - 移动 Safari 独立模式下的可见性变化

javascript - 从 Electron 中所需的 JS 模块访问父变量