簡體   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