我正在尝试将图像保存到数据库,并最终根据用户的用户ID检索它。
我使用了文件选择器,因此我可以从用户的PC获取图像,然后将其转换为Base64字符串,这样我就可以将其传递给webapi,然后将其保存到数据库中。问题是:当选择一个非常大的图像时,它会创建一个非常长的base64字符串,无论它是文本数据类型,它都不能适合数据库字段。请参阅以下代码:
服务器端:
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;
}
存储过程:
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
在我的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");
}
}
我正在使用Angular 5,而我的后端是WebApi。谢谢。