I am learning Blazor Server. I do not have an API project or a controller.
I am trying to modify page Areas/Identity/Pages/Account/Manage/Index.cshtml. I want to add the ability of a user to upload a profile picture and crop it. So I want to send the crop result to the Index.ccshtml.cs PageModel.
I followed a Croppie example here https://github.com/girishgodage/WebCropper/blob/main/WebCropper/Views/Demo/CustomCrop.cshtml but I have to make the Ajax send the crop result to my PageModel instead of a controller.
The Index page already has a post action method, but I need to add another post action method to process the crop result.
Here is my croppie implementation:
<div class="d-flex justify-content-center">
<div class="col-md-6">
<div class="card" style="margin-top:10px;">
<div class="card-header">Cropper in ASP.NET Core</div>
<div class="card-body">
<div id="main-cropper"></div>
<input type="file" id="select" class="form-control" value="Choose Image" accept="image/*">
<button id="btnupload" style="margin-top: 10px;" name="btnupload" class="btn btn-success">Crop</button>
</div>
</div>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js" crossorigin="anonymous"></script>
<script type="text/javascript">
//initialize Croppie
var basic = $('#main-cropper').croppie
({
viewport: { width: 300, height: 300 },
boundary: { width: 500, height: 400 },
showZoomer: true,
url: '/DefaultImages/default-placeholder.png',
format: 'png' //'jpeg'|'png'|'webp'
});
//Reading the contents of the specified Blob or File
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#main-cropper').croppie('bind', {
url: e.target.result
});
}
reader.readAsDataURL(input.files[0]);
}
}
// Change Event to Read file content from File input
$('#select').on('change', function () { readFile(this); });
// Upload button to Post Cropped Image to Store.
$('#btnupload').on('click', function () {
basic.croppie('result', 'blob').then(function (blob) {
var formData = new FormData();
formData.append('filename', 'FileName.png');
formData.append('blob', blob);
//var myAppUrlSettings =
//{
// MyUsefulUrl: '@Url.RouteUrl("Identity/Account/Manage?handler=Crop")'
//}
//var request = new XMLHttpRequest();
//request.open('POST', myAppUrlSettings.MyUsefulUrl);
//request.send(formData);
$.ajax({
type: "POST",
url: "/Account/Manage?handler=Crop",
data: formData,
processData: false,
contentType: false
// url: '/Admin/Users/DeleteUser/OnPost',
})
request.onreadystatechange = function () { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
var response = JSON.parse(request.responseText);
if (response.message == "OK") {
alert('Photo Cropped Successfully!');
window.location.reload();
}
if (response.message == "ERROR") {
window.location.reload();
}
}
}
});
});
</script>
}
public IActionResult OnPostCrop([FromForm] string filename,[FromForm] IFormFile blob)
{
try
{
using (var image = Image.Load(blob.OpenReadStream()))
{
string systemFileExtenstion = filename.Substring(filename.LastIndexOf('.'));
image.Mutate(x => x.Resize(180, 180));
var newfileName180 = GenerateFileName("Photo_180_180_", systemFileExtenstion);
var filepath160 = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Images")).Root + $@"\{newfileName180}";
image.Save(filepath160);
var newfileName200 = GenerateFileName("Photo_200_200_", systemFileExtenstion);
var filepath200 = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Images")).Root + $@"\{newfileName200}";
image.Mutate(x => x.Resize(200, 200));
image.Save(filepath200);
var newfileName32 = GenerateFileName("Photo_32_32_", systemFileExtenstion);
var filepath32 = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Images")).Root + $@"\{newfileName32}";
image.Mutate(x => x.Resize(32, 32));
image.Save(filepath32);
}
//return Json(new { Message = "OK" });
}
catch (Exception)
{
//return Json(new { Message = "ERROR" });
}
return RedirectToPage();
}
public string GenerateFileName(string fileTypeName, string fileextenstion)
{
if (fileTypeName == null) throw new ArgumentNullException(nameof(fileTypeName));
if (fileextenstion == null) throw new ArgumentNullException(nameof(fileextenstion));
return $"{fileTypeName}_{DateTime.Now:yyyyMMddHHmmssfff}_{Guid.NewGuid():N}{fileextenstion}";
}
My Ajax call is giving me an error Request is Not Defined. I have tried various url paths and I cannot figure out what I am doing wrong. Any help would be appreciated.