我在註冊頁面中的asp.net中創建了一個應用程序我想上傳該頁面上的圖片並同時保存在數據庫中,但數據庫工作已經完成了我能夠保存我的上傳圖像,但是無法在該頁面上顯示。在asp.net中上傳時顯示圖像
我的設計代碼:
<form id=`form 1` run at="server">
<div>
<table>
<tr>
<td>
<asp:FileUpload ID="FileUpload1" run at="server" />
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="submit" onclick="Button1_Click" /></td>
<td>
<asp:Label ID="Label1" runat="server" Text="" Font-Names = "Arial"></asp:Label>
<asp:Image ID="Image1" runat="server" Height="52px" Width="79px" />
</td></tr></table>
</div>
</form>
我後面的代碼:
protected void Button 1_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
Image1.ImageUrl = filename;
//Set the contenttype based on File Extension
switch (ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
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 empimage(Name, ContentType, Data)" +
" values (@Name, @ContentType, @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("@Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "File Uploaded Successfully";
}
else
{
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";
}
}
private Boolean InsertUpdateData(SqlCommand cmd)
{
pd = ConfigurationManager.ConnectionStrings["su"].ConnectionString;
con = new SqlConnection(pd);
//String strConnString = System.Configuration.ConfigurationManager
//.ConnectionStrings["conString"].ConnectionString;
//SqlConnection con = new SqlConnection(strConnString);
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();
}
}
,但它並沒有顯示在運行時圖像
請建議我
請參考[此鏈接] [1]。在這裏描述你的問題的答案。 [1]:http://stackoverflow.com/questions/4665160/image-url-is-correct-but-image-not-showing簡要 –