3

我有一个下载处理程序,它会在 IE 中下载文件,但在 chrome 中它会尝试自行下载。我的意思是 Chrome 尝试下载一个名为 downloadhandler.ashx 的文件处理程序的代码是

<%@ WebHandler Language="C#" Class="DownloadHandler" %>
using System;
using System.Web;

public class DownloadHandler : IHttpHandler 
{
public void ProcessRequest(HttpContext context)
{
    string file = "";

    // get the file name from the querystring
    if (context.Request.QueryString["Filepath"] != null)
    {
        file = context.Request.QueryString["Filepath"].ToString();
    }

    string filename = context.Server.MapPath("~/Minutes/" + file);
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(filename);

    try
    {
        if (fileInfo.Exists)
        {
            context.Response.Clear();
            context.Response.AddHeader("Content-Disposition", "inline;attachment; filename=\"" + fileInfo.Name + "\"");
            context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            context.Response.ContentType = "application/octet-stream";
            context.Response.TransmitFile(fileInfo.FullName);
            context.Response.Flush();
        }
        else
        {
            throw new Exception("File not found");
        }
    }
    catch (Exception ex)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write(ex.Message);
    }
    finally
    {
        context.Response.End();
    }
}

public bool IsReusable
{
    get
    {
        return false;
    }
}



}

处理程序从这段代码中接收它的信息

private static string BuildAbsolute(string relativeUri)
{
    // get current uri
    Uri uri = HttpContext.Current.Request.Url;
    // build absolute path
    string app = HttpContext.Current.Request.ApplicationPath;
    if (!app.EndsWith("/")) app += "/";
    relativeUri = relativeUri.TrimStart('/');
    // return the absolute path
    return HttpUtility.UrlPathEncode(
      String.Format("http://{0}:{1}{2}{3}",
      uri.Host, uri.Port, app, relativeUri));
}

此方法中使用的

public static string ToDownloadMinutes(string fileName)
{
    return BuildAbsolute(String.Format("Handlers/DownloadHandler.ashx?Filepath={0}", fileName));
}

任何帮助让这个下载功能在 Chrome 中工作将不胜感激。

4

1 回答 1

6

尝试从 Content-Disposition 标头中删除“inline”,因为“inline”和“attachment”不应该一起使用:

context.Response.AddHeader("Content-Disposition", "attachment; filename=\""
    + fileInfo.Name + "\"");
于 2012-04-04T03:03:30.090 回答