angular-file-upload with ngImgCrop

前端 未结 2 863
一整个雨季
一整个雨季 2021-02-06 11:43

I\'m using (ngImgCrop) to crop an image and then upload the cropped image to server using (angular-file-upload).

I can get the $dataURI from the \"on-change\" option in

2条回答
  •  Happy的楠姐
    2021-02-06 12:24

    try something like:

     var uploader = $scope.uploader = new FileUploader({
            url: '/saveImagePath',
            autoUpload: false
        });
    
    angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);
    
    var handleFileSelect=function(evt) {
          var file=evt.currentTarget.files[0];
          var reader = new FileReader();
          reader.onload = function (evt) {
            $scope.$apply(function($scope){
              $scope.myImage=evt.target.result;
            });
          };
          reader.readAsDataURL(file);
        };
    

    the uploader doesn't support base64 images so you'll need to convert the cropped image from base64 to blob

    function base64ToBlob(base64Data, contentType) {
            contentType = contentType || '';
            var sliceSize = 1024;
            var byteCharacters = atob(base64Data);
            var bytesLength = byteCharacters.length;
            var slicesCount = Math.ceil(bytesLength / sliceSize);
            var byteArrays = new Array(slicesCount);
    
            for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
                var begin = sliceIndex * sliceSize;
                var end = Math.min(begin + sliceSize, bytesLength);
    
                var bytes = new Array(end - begin);
                for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
                    bytes[i] = byteCharacters[offset].charCodeAt(0);
                }
                byteArrays[sliceIndex] = new Uint8Array(bytes);
            }
            return new Blob(byteArrays, { type: contentType });
        }
    

    you have to manually attach the files to the queue like this:

    $scope.submit = function () {
             var file = base64ToBlob($scope.currentPortfolio.croppedImage.replace('data:image/png;base64,',''), 'image/jpeg');
            uploader.addToQueue(file);
            uploader.uploadAll();
    
        };
    

    in the server side, you got two types of files one posted as HTML file and another un base64 which is the cropped image.

提交回复
热议问题