我有一个带有 Image 表的 SQL Server (2008 R2),该表有一个带有 image 类型的列。我使用将我的图像插入此列
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into pm005.images(imageName, type, alt, img)" + " values (@Name, @ContentType, @Alt, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.Add("@Alt", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
private Boolean InsertUpdateData(SqlCommand cmd)
{
// Open a connection the the SQL Server
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=sql-server;integrated security=SSPI;database=pm005";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
我相信这很好用,因为插入返回 true,我可以看到数据库中的数据。
但是,我这辈子都看不到我应该如何恢复这张图片。具体来说,我想要的是能够调用我的网络服务,将 imageID 传递给它,并将图像(并且只有图像)返回给我。就像它用 PHP 完成的一样。这是我现在使用的代码。
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public System.Drawing.Image getImage(int imageID, string uName, string pword)
{
string str="";
try
{
SqlCommand cmd = getSQLCommand("SELECT img FROM pm005.images WHERE id="+imageID);
byte[] Img = (byte[])cmd.ExecuteScalar();
// Convert the image record to file stream and display it to picture control
str = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(str, FileMode.CreateNew, FileAccess.Write);
fs.Write(Img, 0, Img.Length);
fs.Flush();
fs.Close();
}
catch
{
}
finally
{
}
System.Drawing.Image theImage = System.Drawing.Image.FromFile(str);
return theImage;
}
这给出了错误:
System.ArgumentException: The path is not of a legal form.
at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength)
at System.IO.Path.GetFullPathInternal(String path)
at System.IO.Path.GetFullPath(String path)
at System.Drawing.IntSecurity.UnsafeGetFullPath(String fileName)
at System.Drawing.IntSecurity.DemandReadFileIO(String fileName)
at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
at WebService2.Service1.getImage(Int32 imageID, String uName, String pword)
我看了这么多教程,除了“使用 PHP”之外没有找到任何可靠的答案。如果我必须这样做,但肯定有办法在 ASP.NET 中做到这一点?