繁体   English   中英

为什么asp.net下载不起作用?

[英]Why doesn't asp.net download work?

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

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

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
            }

使用以下代码创建流

MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath ).CopyTo(m);
m.WriteTo(Response.OutputStream);

您使用TransmitFile的方向正确。 检查这一行:

Response.ContentType = ContentType;

看起来您要将ContentType设置为页面的默认值。

尝试明确指定它:

Response.ContentType = "image/jpeg";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM