通用处理程序文件下载未开始

问题描述 投票:2回答:2

我正在尝试从服务器开始下载文件,现在只是存在一些文件的硬编码值,但是由于某种原因下载没有开始并且没有引发错误。

这是我的代码:

public void ProcessRequest(HttpContext context)
{
    string destPath = context.Server.MapPath("~/Attachments/cover.txt");
    // Check to see if file exist
    FileInfo fi = new FileInfo(destPath);

    if (fi.Exists)
    {
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + "cover.txt");
        HttpContext.Current.Response.BinaryWrite(ReadByteArryFromFile(destPath));
        HttpContext.Current.Response.End();
    }
}

public bool IsReusable
{
    get
    {
        return false;
    }
}

private byte[] ReadByteArryFromFile(string destPath)
{
    byte[] buff = null;
    FileStream fs = new FileStream(destPath, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    long numBytes = new FileInfo(destPath).Length;
    buff = br.ReadBytes((int)numBytes);
    return buff;
}

我正在输入代码,没有问题,但是浏览器中也没有显示文件下载弹出窗口。

您看到有什么问题吗?

c# httpcontext ashx generic-handler
2个回答
1
投票

我相信您遇到的问题是您打电话给HttpContext.Current。自从您使用Generic Handler File以来,我相信您想利用传递给方法签名的context参数。一个例子是:

public void ProcessRequest (HttpContext context)
{
     // Build Document and Zip:
     BuildAndZipDocument(); 

     // Context:
     context.Response.ContentType = "application/zip";
     context.Response.AddHeader("content-disposition", "filename="Commodity.zip");
     zip.Save(context.Response.OutputStream);

     // Close:
     context.Response.End();
}

我相信如果您使用context,而不是HttpContext.Current,它将解决您的问题。


0
投票

对于您的ZIP文件,请不要在其Content-Type标头中使用“ application / zip”。决不! IE6中已确认的错误将破坏下载。

[如果您希望过去和现在的大多数浏览器中的二进制文件具有最通用的行为,那就总是使用“ application / octet-stream”,就像您在其他地方看到的一样!

header('Content-Type:application / octet-stream');

假设您在乎,这将克服IE6错误。尽管如此,通过从application / octet-stream切换到application / zip,您什么也没有做,所以您最好不要浪费时间在那上面,而将其保留在application / octet-stream上。

© www.soinside.com 2019 - 2024. All rights reserved.