1

I'm using ngImgCrop plugin for image crop and post to my rest service. HTML like this:

<form>
          <button class="btn btn-default fileUpload" type="submit"><span>from pc</span>
            <input type="file"
                   id="fileInput"
                   class="upload"
                   onchange="angular.element(this).scope().uploadFile(this.files[0])"/></button>
          <button class="btn btn-default" type="submit">from camera</button>

          <div class="cropArea">
            <img-crop image="image.myImage" result-image="image.myCroppedImage"></img-crop>
          </div>
          <div class="hidden"><img ng-src="{{image.myCroppedImage}}" ng-model="updatedPhoto" /></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="closeThisDialog(value)">Close
            </button>
            <button type="submit" ng-click="updatePhoto()" class="btn btn-primary">Save</button>
        </form>

And controller.js:

$scope.updatePhoto = function () {
      var updatedPhotoLink = {
      file: file
    };
      $http({
        method: 'POST',
        data:  updatedPhotoLink,
        url: '//myapiservices.com/upload'
      }).then(function successCallback(response) {
       console.log(response);
      }, function errorCallback(response) {
        console.log("error");
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });
    }

Yes, it works but image link return to by base64 but API link want to it by file.

I tried to add for change this:

      var imageBase64 = $scope.image.myCroppedImage;
      var blob = new Blob([imageBase64], {type: 'image/png'});

But its not worked, image file return to blank. How can I convert base64 url to file? Thanks.

4 Answers 4

3

check out this link.

function getBase64Image(base64string) {
    return base64string.replace(/^data:image\/(png|jpg);base64,/, "");
}
var imgData = JSON.stringify(getBase64Image(/* base64string */));
$.ajax({
url: 'http://url.com/rest/api',
dataType: 'json',
data: imgData,
type: 'POST',
 success: function(data) {
  console.log(data);
}
});

this is an example of uploading a image base64 to server, its a bit difference for what you doing but its do the trick.

instead of sending the href of the image you send only the base64 without the metadata in the beginning of the convert base64. you define to contentType:json and you send it to the server.

in the server side you get the base64 (witch it actually a string that represent a bit array) and convert it but to an image (php convert base64)

Sign up to request clarification or add additional context in comments.

Comments

2

Try the following:

<img data-ng-src="data:image/png;base64,{{image.myCroppedImage}}" ng-model="updatedPhoto" />

1 Comment

No, I need image file.
1
 $scope.uploadFileCropper = function () {
        debugger;
        var imageBase64 = $(".cropped")[0].src;
        var blob = this.dataURItoBlob(imageBase64);
        var blobimage = new File([blob], 'image.png');
        if (blobimage != "") {
            var file = blobimage;
            var payload = new FormData();
            payload.append("file", file);
            //data.my_imageurl = $(".cropped")[0].src;
            uploadSUFileService.uploadFile('your API Route', payload).then(function (response) {
                $(".MKloader").fadeOut("slow");
                if (response.status == 200) {
                    $scope.ProductLines.my_imageurl = response.data;
                    document.getElementById('image').src = $scope.ProductLines.my_imageurl;
                    $scope.updatedataimageURl();
                } else if (response.status == 203) {
                    console.log(status);
                    location.replace("/Signin");
                } else if (response.status == 204) {
                    console.log(status);
                    alert("Record not updated")
                }
            }).catch(function (response) {

                console.log(response);
                $(".MKloader").fadeOut("slow");
            });
        }
    }

 $scope.dataURItoBlob = function (dataURI) {
        var byteString = atob(dataURI.toString().split(',')[1]);

        //var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

        var ab = new ArrayBuffer(byteString.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        var blob = new Blob([ab], { type: 'image/png' }); //or mimeString if you want
        return blob;
    }

1 Comment

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
0

you added this:

var imageBase64 = $scope.image.myCroppedImage;
var blob = new Blob([imageBase64], {type: 'image/png'});

now some changes:

var imageBase64 = $scope.image.myCroppedImage;
var blob = this.dataURItoBlob(imageBase64);
var image = new File([blob], 'image.png');

and add this function:

dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.toString().split(',')[1]);

    //var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    var blob = new Blob([ab], {type: 'image/png'}); //or mimeString if you want
    return blob;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.