我的viewdepositslip.aspx有这个代码,其中显示了存储上传文件的文件夹中的图像:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded">
<Columns>
<asp:BoundField DataField="Text" HeaderText="File Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID = "lnkDelete" Text = "Delete" CommandArgument = '<%# Eval("Value") %>' runat = "server" OnClick = "DeleteFile" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
这是我将图像上传到文件夹的代码(这是来自客户端,不同的网络表单)。
protected void UploadFile(object sender, EventArgs e)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
这就是背后的代码。那么删除按钮功能完美但我无法使下载链接功能正常工作。我在这里错过了什么?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/BankDepositUploads/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
}
protected void DeleteFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
File.Delete(filePath);
Response.Redirect(Request.Url.AbsoluteUri);
}
此外,我计划在网格视图中显示实际图像。截至目前,它有图片网址。
答案 0 :(得分:1)
您的代码也应该有效,但由于任何原因它可能无法正常工作,请尝试这样:
aspx页面
<asp:LinkButton ID="lnkDownload" runat="server" CommandName="cmd">Download</asp:LinkButton>
CS页面
protected void GridView1_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "cmd")
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
}
}
修改: - 强> 由于您使用的是更新面板,因此您在单击链接按钮时会进行回发。有很多方法可以做到这一点。我正在解释两种方式。 将此代码放在页面加载
ScriptManager.GetCurrent(this).RegisterPostBackControl(this.GridView1);
或者在</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="GridView1" />
</Triggers>