将图片保存在文件夹中并以网格视图显示

时间:2014-11-28 04:29:51

标签: asp.net database vb.net gridview

我的页面上有这些控件:

<p>
    <asp:FileUpload ID="FileUpload1" runat="server" />
</p>
<p>
    <asp:Button ID="Button1" runat="server" Text="Button" />
</p>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

有一个名字&#34; UplPics&#34;在我的解决方案资源管理器和我的Defaul.aspx页面中的以下VB.NET代码中:

Imports System.IO

Partial Class _Default

 Inherits System.Web.UI.Page

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     If Not IsPostBack Then
         Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/UplPics/"))
         Dim files As New List(Of ListItem)()
         For Each filePath As String In filePaths
             Dim fileName As String = Path.GetFileName(filePath)
             files.Add(New ListItem(fileName, "~/UplPics/" + fileName))
         Next
         GridView1.DataSource = files
         GridView1.DataBind()
     End If

 End Sub

 Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
     If FileUpload1.HasFile Then
         Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
         FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UplPics/") + fileName)
         Response.Redirect(Request.Url.AbsoluteUri)
     End If

 End Sub 
End Class

当我上传并加载我的网页时,它不显示图片但显示每张图片的网址,我该如何显示图片而不是网址?

1 个答案:

答案 0 :(得分:1)

GridView绑定到该数据源控件之后。这个GridView有1个BoundField列,这意味着在浏览器中查看GridView时,我们不会看到实际的图像,而是看到实际的图像路径。未注明图像路径列的列名。

现在,要显示实际图像,我们需要编辑GridView的列,添加一个新的BoundField说ImageField。然后,将ImageField的DataImageUrlField设置为包含图像路径的DataSource字段的名称(上面列出的列名称)。

http://msdn.microsoft.com/en-us/library/aa479350.aspx