0

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

只有在文件完全上传后,我才能使这样的链接可见?

4

1 回答 1

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;
            }
        }
    }
}
于 2012-12-14T20:42:35.477 回答