I'm trying to add Image Upload with Froala Editor to my Blog app.
My onPost method in NewPost.cshtml.cs file looks like this:
public async Task<IActionResult> OnPostUploadImageAsync(IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest("No file uploaded");
}
try
{
var uploadResult = await _imageRepository.UploadAsync(file);
if (uploadResult == null || string.IsNullOrEmpty(uploadResult.SecureUrl.AbsoluteUri))
{
return BadRequest("Failed to upload image");
}
return new JsonResult(new { url = uploadResult.SecureUrl.AbsoluteUri });
}
catch (Exception ex)
{
// Log the exception here
return BadRequest("An error occurred while uploading the image");
}
}
And in my NewPost.cshtml file js script looks like this:
<script>
var editor = new FroalaEditor('#content', {
height: 300,
imageUploadURL: '/Admin/NewPost?handler=OnPostUploadImageAsync',
})
document.getElementById('featuredImageUpload').addEventListener('change', function () {
var input = this;
var imgPreview = document.getElementById('featuredImagePreview');
var imageURLInput = document.getElementById('featuredImageURL');
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
imgPreview.src = e.target.result;
};
reader.readAsDataURL(input.files[0]);
imageURLInput.value = '@ViewData["FeaturedImageURL"]';
}
});
</script>
Now when i try to upload an image by froala I get 'Error during file upload' and in Chrome Console POST https://localhost:7006/Admin/NewPost?handler=OnPostUploadImageAsync 400 (Bad Request)
When I tried debugging I saw that the code in NewPost.cshtml.cs is unreachable, but I still did not find a solution.