I have an image editor with a button, when the button is pressed it saves the image to a folder on the server.
It works in most cases, although sometimes it throws an Http 400 error.
How do I add error handling so I can present a nice message to the user?
It seems the error happens when the image size (height and/or width) is exceptionally big, is that the case?
here's my code:
<form method="post">
<input type="hidden" asp-for="editedFileName" />
<input type="hidden" asp-for="ImagePath" />
<div class="admin-button-container align-right">
<button type="submit" class="btn btn-theme-admin">Save Image</button>
</div>
<div class="imageEditor"></div>
</form>
my js:
$(document).ready(function() {
var OpenExecuted = false;
// page load
showImgOption();
});
function onSelect(e) {
$('#editedFileName').val(e.files[0].name);
}
function handleUploadImageEvents(imageEditor) {
OpenExecuted = true;
imageEditor._upload.bind("select", onSelect);
}
function onImageRendered(e) {
zoom();
saveImagePath();
};
function onExecute(e) {
if (e.command === "OpenImageEditorCommand") {
setTimeout(function() {
handleUploadImageEvents(e.sender);
});
}
};
// this function will zoom out the photo if the height is more than 600px
// so that it does not overlap other fields on the page
function zoom() {
var imgEditor = $('.imageEditor').data('kendoImageEditor');
imgEditor.executeCommand({ command: "ZoomImageEditorCommand", options: imgEditor.zoom = 1 });
var imgHt = $(".k-imageeditor-canvas").height();
if (imgHt > 600) {
imgEditor.executeCommand({ command: "ZoomImageEditorCommand", options: imgEditor.getZoomLevel() - 0.5 });
}
};
function ImgEditor() {
$(`.imageEditor`).kendoImageEditor({
toolbar: {
items: [
"open",
"save",
"crop",
"resize",
"undo",
"redo",
"zoomIn",
"zoomOut",
"zoomDropdown",
]
},
messages: {
toolbar: {
open: "Upload"
},
},
imageUrl: $('[id="ImagePath"]').val(),
height: 650,
error: onError,
imageRendered: onImageRendered,
execute: onExecute,
});
}
function onError(e) {
console.log('Error');
};
function showImgOption() {
var imgFilePath = $('[id="ImagePath"]').val();
if (imgFilePath.length > 0) {
var imgFilename = imgFilePath.slice(imgFilePath.lastIndexOf("/") + 1, imgFilePath.length + 1);
$('[id="FileName"]').val(imgFilename);
}
ImgEditor();
}
function saveImagePath() {
const imageEditor = $('.imageEditor').data('kendoImageEditor');
const image = imageEditor.getCurrentImage();
const imageObject = new DOMParser().parseFromString(image, "text/xml");
const canvas = imageEditor.getCanvasElement();
const fileArray = canvas.toDataURL().split(",");
const base64String = canvas.toDataURL();
const imagePathSaved = $('[id="ImagePath"]').val(fileArray[1]);
}