I am trying to save an image to a database and ultimately retrieve it based on the User Id of the user.
I used the file selector so I can get the image from the user's pc then convert it to Base64 string so I can pass it to the webapi then will be saved to the database. The problem is: when a pretty large image is selected, it creates a very long base64 string that can't fit in a database field whether it be a text data type. Please see code below:
Server side:
public int EditAccount(NewData newData, string image)
{
var result = 0;
//if (UserNameExists(newData.UserName)) return "Username is already taken";
using (var cmd = new SqlCommand("UpdateUserAccount", _dbConnection) { CommandType = CommandType.StoredProcedure})
{
try
{
_dbConnection.Open();
cmd.Parameters.AddWithValue("@UserId", newData.UserId);
cmd.Parameters.AddWithValue("@UserName", newData.UserName);
cmd.Parameters.AddWithValue("@Email", newData.Email);
cmd.Parameters.AddWithValue("@Image", image);
result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
result = 0;
}
finally
{
_dbConnection.Close();
}
}
return result;
}
Stored procedure:
ALTER PROCEDURE [dbo].[UpdateUserAccount]
(@UserId NVARCHAR(128),
@UserName NVARCHAR(256),
@Email NVARCHAR(256),
@Image TEXT)
AS
BEGIN
UPDATE [User]
SET UserName = @UserName, Email = @Email
WHERE Id = @UserId
SELECT COUNT(Id)
FROM UserImage
WHERE UserId = @UserId
IF (SELECT 1 FROM UserImage WHERE UserId = @UserId) = 1
BEGIN
UPDATE [UserImage]
SET UserImage = @Image
WHERE UserId = @UserId
END
ELSE
BEGIN
INSERT INTO [UserImage] (UserId, UserImage)
VALUES (@UserId, @Image)
END
END
In my component.ts:
OnSubmit(form: NgForm) {
this.userService.updataUserAccount(form.value, this.base64textString)
.subscribe((data: any) => {
if (data === 1) {
this.userClaims.UserName = this.newData.UserName;
this.userClaims.Email = this.newData.Email;
this.resetForm(form);
this.editMode = false;
this.toastr.success("Successfully edited data");
}
else
this.toastr.error(data.Errors[0]);
});
}
// file handler
handleFileSelect(evt){
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload =this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
_handleReaderLoaded(readerEvt) {
console.log("Even Happened");
var binaryString = readerEvt.target.result;
var x = btoa(binaryString);
if(x != this.base64textString){
this.base64textString= btoa(binaryString);
console.log("No Match");
}
}
I am using Angular 5 for this and my backend is WebApi. Thank you.