I am trying to use ngx-image-cropper to upload images on my application, but I cannot save the cropped image. For example, if I try to save the main file (the file which is loaded through the input type="file"), everything works fine. In this case, the file is sent like this:
{name: "300_3.jpg",
lastModified: 1510510128437,
lastModifiedDate: Sun Nov 12 2017 20:08:48 GMT+0200 (GTB Standard Time), webkitRelativePath: "",
size: 81972, …}
But if I try to upload the cropped version of the image, the file looks like this:
data:image/png;base64,iVBORw0KGgoAAAANSU............
And the response from the server is something like:
{error: "Bad Request",
exception:"org.springframework.web.multipart.support.MissingServletRequestPartException",
message: "Required request part 'file' is not present",
path: "/api/myEndPoint/",
status: 400,
timestamp: 1518424822285}
So basically I need to send an abject as in the first case, but all I have is a base64 item.
Here is also the HTML code, in case it helps:
<image-cropper
[imageChangedEvent]="imageChangedEvent"
[maintainAspectRatio]="true"
[aspectRatio]="4 / 4"
[resizeToWidth]="250"
format="png"
(imageCropped)="imageCropped($event)"
(imageLoaded)="imageLoaded()"
(loadImageFailed)="loadImageFailed()"
*ngIf="isUploadedFile">
</image-cropper>
Can someone please advise how may I upload the cropped version and not the initial file I uploaded? Or is this something which needs to be fixed on the server, so it can accept the file I sent? Thanks!
That string:
data:image/png;base64,iVBORw0KGgoAAAANSU............
means that you have your cropped image as dataURI. If you want to bring your upload of cropped image to work, then you should convert it from dataURI to Blob. If you have done this, then you can create from Blob an File and upload this to server.
Here is a function for converting dataURI to Blob:
dataURItoBlob(dataURI): Blob {
const byteString = atob(dataURI.split(',')[1]);
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
const ab = new ArrayBuffer(byteString.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: mimeString });
}
And now you can create File and upload it to server. Here is an example of uplaod function:
uploadAttachmentToServer() {
const fileToUpload: File = new File([this.dataURItoBlob(yourCroppedImage)], 'filename.png');
this.attachmentService.postAttachment(fileToUpload).subscribe(data => {
// success, do something
}, error => {
// failure, do something
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With