我在一个ImageButton控件中有一个ListView控件,单击该控件时,应该下载具有正确ID的图像。
以下是ImageButton ASPX:
<asp:ImageButton runat="server" ID="ibtDownloadImage" ImageUrl="img/downloadIcon.png" OnClick="ibtDownloadImage_OnClick" CommandArgument='<%# Convert.ToString(Eval("ID"))+Convert.ToString(Eval("FileExtension")) %>' />如您所见,单击它时,它执行"ibtDownloadImage_OnClick“方法,并将命令参数设置为ID加上FileExtension (例如,1.jpg,它是图像的名称)。
我用于C#的ibtDownloadImageOnClick代码是:
protected void ibtDownloadImage_OnClick(object sender, EventArgs e)
{
ImageButton img = (ImageButton)sender;
string file = img.CommandArgument;
String imgURLtoDownload = @"img/uploads/"+file;
Response.AddHeader("Content-Disposition", "attachment; filename=" + imgURLtoDownload);
}当我单击ImageButton控件时,它下载了一个名为“img-upads-1.jpg”的文件(没有语音标记),因此它似乎将我想要的文件作为文件名的一部分,并将/替换为-.
有什么办法解决这个问题吗?这看起来应该是一个简单的解决方案。
我在Response.AddHeader行上运行了一个断点的调试,imgURLtoDownload的内容是img/upload/1.jpg (应该是这样)。
发布于 2014-10-30 15:59:29
您可以将文件内容读取为二进制,假设您有此函数,该函数以文件名get字节数组作为二进制内容,函数名为GetFileContent(Filepath)。然后,您可以使用该函数将内容写入响应,然后指定自定义路径。
ImageButton img = (ImageButton)sender;
string file = img.CommandArgument;
String imgURLtoDownload = @"img/uploads/"+file;
byte[] data= GetFileContent(Server.MapPath(imgURLtoDownload));
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file);
Response.ContentType = System.Web.MimeMapping.GetMimeMapping(Server.MapPath(imgURLtoDownload));
Response.BinaryWrite(data);
Response.End();
public byte[] GetFileContent(string Filepath)
{
return System.IO.File.ReadAllBytes(Filepath);
}https://stackoverflow.com/questions/26657700
复制相似问题