Donaldcwl / browser-image-compression

Image compression in web browser
MIT License
1.3k stars 160 forks source link

How can i run this script with AJAX post? #160

Closed Kepron closed 2 years ago

Kepron commented 2 years ago

I'm trying to use the script with ajax but failed. I'm still a beginner with Javascript. Where am I doing wrong?

https://jsfiddle.net/rd8f6vqu/2/

function addImage (image_type, game) {
    var confirmText = 'Submit';
    var cancelText = 'Cancel';
    var main_title = 'Title';
    var img_icon = '<span class="material-symbols-outlined gp-imageupload-titleicon">swords</span>';
    Swal.fire({
      customClass: {
        container: 'gp-imageupload-body',
        popup: 'swall-custom-backgroundcolor swall-custom-border',
        title: 'swall-custom-title',
        htmlContainer: 'swall-custom-textcolor',
        icon: 'swall-custom-icon',
        validationMessage: 'swall-custom-validatormsg',
      },
      title: main_title,
      iconHtml: img_icon,
      html:
      '<div class="gp-imageupload-box">' +
          '<form action="#" id="gp-imageupload-sendForm">' +
              '<div id="gp-imageupload-drop-area">' +
                  '<label for="gp-imageupload-fileElem">' +
                      '<input type="file" name="uploaded_image" id="gp-imageupload-fileElem" onchange="handleFiles(this.files)" />' +
                      '<div class="uploadIcon">' +
                          '<i class="fa fa-cloud-upload fa-4x" aria-hidden="true"></i>' +
                          '<p>Paste Image <span class="or">or</span> Drag & Drop <span class="or">or</span> Click & Select</p>' +
                          '<p class="last">Only jpeg, jpg and png</p>' +
                      '</div>' +
                      '<div id="gp-imageupload-gallery"></div>' +
                  '</label>' +
                  '<div class="gp-imageupload-control-panel">' +
                      '<div class="item">' +
                          '<div id="delete-image"><span class="material-symbols-outlined">delete_forever</span></div>' +
                      '</div>' +
                  '</div>' +
              '</div>' +
              '<div class="progress-wrapper">' +
                '<div class="progress-info">' +
                  '<div class="progress-percentage">' +
                    '<span class="text-sm font-weight-bold" id="gp-imageupload-progressbar-span">0%</span>' +
                  '</div>' +
                '</div>' +
                '<div class="progress">' +
                  '<div class="progress-bar bg-primary" id="gp-imageupload-progressbar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
                '</div>' +
              '</div>' +
              '<div id="gp-imageupload-details_img">' +
                  '<div class="list">' +
                      '<div class="item">' +
                          '<div class="attr">Name</div>' +
                          '<div class="data" id="nameImage">No Data</div>' +
                      '</div>' +
                      '<div class="item">' +
                          '<div class="attr">Size</div>' +
                          '<div class="data" id="sizeImage">No Data</div>' +
                      '</div>' +
                      '<div class="item">' +
                          '<div class="attr">Type</div>' +
                          '<div class="data" id="typeImage">No Data</div>' +
                      '</div>' +
                  '</div>' +
              '</div>' +
          '</form>' +
      '</div>' +
      '<div id="gp-imageupload-container-image"></div>',
      showCloseButton: false,
      showCancelButton: true, 
      focusConfirm: false,
      confirmButtonText: confirmText,
      cancelButtonText: cancelText,
      showLoaderOnConfirm: true,
      preConfirm: function() {
        var ext = $('#gp-imageupload-fileElem').val().split('.').pop().toLowerCase();
        console.log(ext);
        if($.inArray(ext, ["jpg","jpeg","png"]) == -1) {
          Swal.showValidationMessage(
            `Error`
          )
        }

      },
      }).then((result) => {
        if(result.value){
          var file_input = $('#gp-imageupload-fileElem');
          var progress_bar = $('#gp-imageupload-progressbar');
          var progress_percent = $('#gp-imageupload-progressbar-span');
          var original_file = $('#gp-imageupload-fileElem')[0].files[0];
          const options = {
            maxWidthOrHeight: 1000,
            useWebWorker: true
          }

          imageCompression(original_file, options)
          .then(function (compressedFile) {
              return uploadToServer(compressedFile); // write your own logic
          })
          .catch(function (error) {
              console.log(error.message); // output: I just want to stop
          });

          var filedata = new FormData();
          filedata.append('game', game);
          filedata.append('data', image_type);
          filedata.append('input_val', "image");
          filedata.append('file', compressed_file);

          $.ajax({
            url: 'editimage.php',
            type: 'POST',
            data: filedata,
            dataType: "json",
            cache:false,
            contentType: false,
            processData: false,
            beforeSend: function() {
                var percentVal = '0%';
                var percentVal2 = '0';
                progress_bar.attr("aria-valuenow", percentVal2);
                progress_bar.css("width", percentVal);
                progress_percent.text(percentVal);
            },
            uploadProgress: function(event, position, total, percentComplete) {
                var percentVal = percentComplete + '%';
                progress_bar.attr("aria-valuenow", percentComplete);
                progress_bar.css("width", percentVal);
                progress_percent.text(percentVal);
            },
            complete: function(xhr) {
              var percentVal = '100%';
              var percentVal2 = '100';
                progress_bar.attr("aria-valuenow", percentVal2);
                progress_bar.css("width", percentVal);
                progress_percent.text(percentVal);
            },
            success: function(result){
              if (result.status == true) {

              }
              else {

              }                 
            }
          });
        }else {
            window.removeEventListener('paste', pasteImage);
        }
    });
    window.nodata_text = 'No Data';
    $.getScript( "/assets/js/imageuploader.js?ver=111" )
      .done(function( script, textStatus ) {
        console.log( textStatus );
      })
      .fail(function( jqxhr, settings, exception ) {
        $( "div.log" ).text( "Triggered ajaxError handler." );
    });
  };
Kepron commented 2 years ago

I figured out. This happens because of Promise. Here is the working code.

imageCompression(original_file, options)
        .then(function (compressedFile) {
          console.log('compressedFile instanceof Blob', compressedFile instanceof Blob); // true
          console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeM
          var file_Type = compressedFile.type.split('/').pop().toLowerCase();
          var filedata = new FormData();
          filedata.append('game', game);
          filedata.append('data', image_type);
          filedata.append('input_val', "image");
          filedata.append('file', compressedFile);
          filedata.append('file_type', file_Type);

          ajaxpost(filedata);
        })
        .catch(function (error) {
            console.log(error.message); // output: I just want to stop
        });

        function ajaxpost (dataForm) {
          $.ajax({
              // some ajax code
          });
        }