为什么没有asp.net下载工作?

时间:2016-03-28 10:30:57

标签: c# asp.net c#-4.0 gridview c#-3.0

我正在使用此代码下载图像,即我将带​​有扩展名的图像名称存储在数据库中并将其存储在此处。

此代码不会引发任何错误,但不会下载任何内容。为什么?

try {
    if (e.CommandName == "Download")
    {
        string ImgPath = Convert.ToString(r["Attachment"]);
        //string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");

        //string filePath = ImgName + ".jpg";
        string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
        Response.ContentType = ContentType;
        Response.TransmitFile(fullFilePath); //downloads file
        Response.Flush();

        //FileInfo file = new FileInfo(fullFilePath);
        //file.Delete(); //deletes file after downloading
    }
}
catch (Exception ex)
{
    ResultLabel.ResultLabelAttributes(ex.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
}
finally 
{
    ResultPanel.Controls.Add(ResultLabel);
}

更新:

我试过这个但是没有用。

 if (e.CommandName == "Download")
            {
                string ImgPath = Convert.ToString(r["Attachment"]);
                //string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");


                        //string filePath = ImgName + ".jpg";
                        MemoryStream m = new MemoryStream();
                        File.OpenRead(ImgPath).CopyTo(m);
                        m.WriteTo(Response.OutputStream);

                        string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
                        Response.Clear();
                        Response.ClearHeaders();
                        Response.ClearContent();
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
                        Response.ContentType = ContentType;
                        Response.TransmitFile(fullFilePath); //downloads file
                        Response.Flush();

                        //FileInfo file = new FileInfo(fullFilePath);
                        //file.Delete(); //deletes file after downloading
            }

2 个答案:

答案 0 :(得分:0)

使用以下代码

创建一个流
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath ).CopyTo(m);
m.WriteTo(Response.OutputStream);

答案 1 :(得分:0)

您使用TransmitFile走上了正确的轨道。检查这一行:

Response.ContentType = ContentType;

您似乎正在将ContentType设置为页面的默认设置。

尝试明确指定:

Response.ContentType = "image/jpeg";