使用FileUpload上传文件后显示链接

时间:2012-12-14 19:00:23

标签: javascript asp.net

我正在使用FileUpload上传文件。文件上传后,我希望用户看到一个“删除”链接,该链接将从服务器中删除该文件。

如果文件完全上传后,我怎样才能看到这样的链接?

1 个答案:

答案 0 :(得分:1)

我尝试过使用数据控件来实现这一目标。

 <asp:Panel ID="pnlUpload" runat="server">
    <asp:FileUpload ID="fup1" runat="server" ClientIDMode="Static" />
    <asp:Button ID="btnServer" runat="server" Text="Submit" OnClick="btnSubmit_Click"
        ClientIDMode="Static" CssClass="none" />
</asp:Panel>
<asp:Repeater ID="rptUploads" runat="server" OnItemCommand="rptUploads_ItemCommand">
    <HeaderTemplate>
        <table width="100%">
            <th>
                File Name
            </th>
            <th>
                Actions
            </th>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>
                <%# Container.DataItem %>
            </td>
            <td>
                <asp:LinkButton ID="LinkButton1" runat="server" Text="Remove" CommandName="Delete"
                    CommandArgument="<%# Container.DataItem %>"></asp:LinkButton>
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>
<style>
    .none
    {
        display: none;
    }
</style>
<script type="text/javascript">
    (function () {
        if (document.getElementById('fup1') != null) {
            document.getElementById('fup1').onchange = function () { document.getElementById('btnServer').click(); };
        }
    })();
</script>

背后的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;

public partial class _Default : System.Web.UI.Page
{
    public List<string> Files
    {
        get
        {
            if (ViewState["files"] == null)
            {
                ViewState["files"] = new List<string>();
            }
            return (List<string>)ViewState["files"];
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (fup1.HasFile && !Files.Contains(fup1.FileName))
        {
            fup1.SaveAs(Server.MapPath("~/App_Data/") + fup1.FileName);
            Files.Add(fup1.FileName);
            rptUploads.Visible = true;
            rptUploads.DataSource = Files;
            rptUploads.DataBind();
            pnlUpload.Visible = false;
        }
    }

    protected void rptUploads_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            var filename = Server.MapPath("~/App_Data/") + e.CommandArgument;
            if (File.Exists(filename))
            {
                File.Delete(filename);
                Files.Remove(e.CommandArgument.ToString());               
                rptUploads.Visible = false;
                pnlUpload.Visible = true;
            }
        }
    }
}