【发布时间】:2021-11-26 01:58:10
【问题描述】:
我按照本指南中的代码来调整图像的大小,然后再将其存储到数据库中: https://www.aspsnippets.com/questions/876401/Resize-image-and-save-into-Database-with-Binary-format-using-C-and-VBNet-in-ASPNet/
代码如下:
protected void Save(object sender, EventArgs e)
{
if (fuImage.HasFile)
{
Byte[] bytes;
string contentType = fuImage.PostedFile.ContentType;
string fileName = Path.GetFileName(fuImage.FileName);
string filePath = fuImage.PostedFile.FileName;
System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
// Resize image
using (System.Drawing.Image thumbnail = image.GetThumbnailImage(130, 170, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
{
using (MemoryStream memoryStream = new MemoryStream())
{
thumbnail.Save(memoryStream, ImageFormat.Png);
bytes = new Byte[memoryStream.Length];
memoryStream.Position = 0;
memoryStream.Read(bytes, 0, (int)bytes.Length);
}
}
// Insert uploaded image to Database
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO tblFiles1 VALUES (@Name, @ContentType, @Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", fileName);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
// Display image after upload to Database
Image1.Visible = true;
byte[] byteData = (byte[])GetData("SELECT Data FROM tblFiles1").Rows[0]["Data"];
string base64String = Convert.ToBase64String(byteData, 0, byteData.Length);
Image1.ImageUrl = "data:image/png;base64," + base64String;
}
public bool ThumbnailCallback()
{
return false;
}
然而,我遇到的问题是,一旦我使用 FileUploader 选择了一个图像并尝试运行 save 方法,我在该行得到一个 System.IO.FileNotFoundException:
System.Drawing.Image image = System.Drawing.Image.FromFile(filePath);
提前致谢!
【问题讨论】:
-
调试的时候
filePath的值是多少?您确认那里有文件吗? -
filepath的值有正确的图片名称,我检查了
-
您好,谢谢,我知道将图像存储在数据库中并不是一个好习惯,但这是针对大学项目的,因此不是正常情况哈哈
-
错误提示文件不存在。我们不需要查看您的任何其他代码:读/写数据库;处理图像;等等。只需专注于从磁盘文件中读取图像。你是通过相对路径吗?绝对?在网络上?尝试传入您编写的一些特定路径,看看会发生什么。只需编写一个方法来打开文件并从中进行故障排除。
标签: c# asp.net file-upload runtime-error