How to handle http 400 error when saving an image from Image Editor to the server?

2 Answers 49 Views
ImageEditor
Lindsay
Top achievements
Rank 1
Iron
Lindsay asked on 26 Sep 2024, 06:37 PM

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]);
}


2 Answers, 1 is accepted

Sort by
0
Accepted
Lindsay
Top achievements
Rank 1
Iron
answered on 01 Oct 2024, 09:11 PM

What I ended up doing to get around it was check the size of the dimensions, very similar to what Mihaela posted. 

I used the dimensions because the file size seemed to vary a lot in what was accepted versus what was not accepted, and this worked well enough for my needs.

here's my js code to prevent the error:

 


$("#btnSaveImg").on("click", function(e) {
	// the page throws an error when the filesize and/or dimensions are too big, so I'm limiting them before saving
	if ($('.k-imageeditor-canvas').width() == 0 || $('.k-imageeditor-canvas').height() == 0) {
		e.preventDefault();
		alert("Please upload an image.");
	}

	var canvas = $('.k-imageeditor-canvas canvas');
	var widthAttr = canvas.attr('width');
	var heightAttr = canvas.attr('height');
	
	if (widthAttr > 1920 || heightAttr > 650) {
		e.preventDefault();
		alert("The image dimensions exceed the allowed size of 1920x650. Cannot save the file.");
	}
});

 

Mihaela
Telerik team
commented on 02 Oct 2024, 07:02 AM

Thank you for sharing your solution, Lindsay. It is greatly appreciated!
0
Mihaela
Telerik team
answered on 01 Oct 2024, 06:19 PM

Hello Lindsay,

Indeed, the bad request could be related to the image size being too large. I have tested the case with a 2MB image, and the request was successful. However, the payload size limit may be reached when submitting a large-size image.

You can validate the size of the image before submitting the form. For example:

<div id="error-message" style="color: red; display: none;"></div>
<form method="post">
	...
</form>

$(document).ready(function () {
		var OpenExecuted = false;
		//  page load
		showImgOption();

		$("form").on("submit", function (e) {
			e.preventDefault(); // prevent the default form submission
			var image = $('[id="ImagePath"]').val();
			const decoded = window.atob(image);
			const size = decoded.length;
			if(size > 20000) { // check if the image size is > 20000 bytes
				$('#error-message').text('File size exceeds the limit.').show(); // show an error message above the form
			} else {
                                $('#error-message').hide();
				$("form").off("submit"); //remove the "submit" event handler
				$(this).submit(); //submit the form
			}
		});
	});

Also, you can use the Notification component to show the error message.

If you have any additional questions, please let me know.

Regards,
Mihaela
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Lindsay
Top achievements
Rank 1
Iron
commented on 01 Oct 2024, 09:12 PM

Thank you Mihaela! I haven't tried this out, but it looks really similar to what I did.
Tags
ImageEditor
Asked by
Lindsay
Top achievements
Rank 1
Iron
Answers by
Lindsay
Top achievements
Rank 1
Iron
Mihaela
Telerik team
Share this question
or