在我对(gridview 中上传文件的图标)有疑问并收到以下代码之前。
这段代码似乎适用于我们在服务器中保存文件时。现在,如果我们将文件保存在数据库中,我必须如何更改代码。
using System.Drawing;
using System.IO;
public string GetIconFromFile()
{
Icon ic = Icon.ExtractAssociatedIcon(Server.MapPath (".")+"/Files/Test.txt");
string imagePath=Server.MapPath(".") + "/Images/Test.ico";
if (ic != null)
{
using (FileStream stream = new FileStream(imagePath, FileMode.OpenOrCreate))
{
ic.Save(stream);
}
}
return imagePath ;
}
protected void GridViewEfile_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img = (System.Web.UI.WebControls.Image)e.Row.FindControl("Image1");
img.ImageUrl = GetIconFromFile();
}
}
.aspx
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" OnCommand="LinkButton1_Command" CommandName="Download" CommandArgument='<%#Eval("FileID")%>'><%#Eval("FileName")%></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
当我想保存在数据库中时,上传按钮的代码如下所示,请帮助改变函数(GetIconFromFile()),特别是当我们需要 filename.ico
protected void btnUpload_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;
//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