2
我有一個帶有圖像表的SQL Server(2008 R2),表中有一個帶有類型圖像的列。我插入我的圖片到使用使用ASP.NET Web服務從SQL Server檢索圖像
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,我可以在數據庫中看到的數據。
但是我不能爲我的生活看到我應該如何讓這個圖像退出。具體來說,我想要的是能夠調用我的Web服務,將它傳遞給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中做到這一點?
沒有完整路徑,圖像存儲在數據庫中 – 2013-04-08 03:40:44
當您從數據庫中檢索圖像時,試圖將其寫入磁盤。我可以在調用堆棧中看到它在這裏失敗:'System.Drawing.Image.FromFile'。你可以仔細檢查你正在使用FileStream方法的第6重載,它需要參數中第一個參數的filePath? – 2013-04-08 03:43:24
是的,但這只是因爲教程告訴我。我不知道爲什麼我只是把時間傳遞給我。 – 2013-04-08 03:46:42