【发布时间】:2021-09-01 17:07:41
【问题描述】:
我在将图像转换为 Base64 字符串并将其作为字符串保存在数据库中时遇到问题,但它没有返回任何内容。 Base64Text 是全局变量,变量不为空我用按钮填充文本框测试它,它只是保存为“”到数据库中。
这是数据库中的表模型
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
public double ProductPrice { get; set; }
public int ProductAmount { get; set; }
public string ProductImage { get; set; } // Used for storing image string
public int userID { get; set; }
}
// Here is image converter
private void btnAddImage_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image Files(*.BMP;*.JPG;*.PNG;*.JPEG)|*.BMP;*.JPG;*.PNG;*.JPEG" +
"|All files(*.*)|*.*";
dialog.CheckFileExists = true;
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
var image = new Bitmap(dialog.FileName);
pictureBoxProductImage.Show();
pictureBoxProductImage.Image = (Image)image;
byte[] imageArray = System.IO.File.ReadAllBytes(dialog.FileName);
base64Text = Convert.ToBase64String(imageArray);
}
}
// Here is saving image using Entity framework
private void btnAddProduct_Click(object sender, EventArgs e)
{
string imagePath = base64Text;
if (txtBoxProductName.Text == null || txtBoxProductPrice.Text == null || txtBoxProductQuantity.Text == null || imagePath == null || imagePath == "")
{
MessageBox.Show("Please fill required information!", "", MessageBoxButtons.OK);
}
else
{
model.ProductName = txtBoxProductName.Text;
model.ProductPrice = Convert.ToDouble(txtBoxProductPrice.Text);
model.ProductAmount = Convert.ToInt32(txtBoxProductQuantity.Text);
model.ProductImage = imagePath;
model.userID = id;
using (var context = new ProductContext())
{
context.Products.Add(model);
context.SaveChanges();
}
MessageBox.Show("Product sucesffuly added to database!", "", MessageBoxButtons.OK);
Clear();
}
}
【问题讨论】:
-
乍一看,我注意到您正在将整个图像转换为base64,而不仅仅是路径!其次,你能告诉我们 DbContext 吗?保存操作后您是否查看了数据库的内容?
-
所有其他数据都正确保存为书面预期图像字符串“”,所以我需要保存路径而不是 base64string?
-
您能否提供有关您所针对的 EF 版本以及您使用的数据库的更多信息? binaryintellect.net/articles/…我建议按照上面的例子......特别注意从内存流复制到方法的实体配置和字节数组
-
在哪里实例化产品实体?可能是您在保存后将其图像属性设置在其他位置,EF 仍然跟踪该对象,并且在另一个保存事务中它被重置为 null
-
由于您将整个图像保存为 base64 不仅是路径,我认为您可能会在表格中遇到一些限制,因为结果 base64 会很长。我建议您只保存路径或使用其他数据类型来存储二进制文件 - 如果文件在所有机器上本地不可用或在线不可用 -。
标签: c# database winforms entity-framework tobase64string