简体   繁体   中英

ASP.NET Download Handler Works in IE but not Chrome

I have a download handler that will download the file when in IE but in chrome it attempts to download itself. By this I mean Chrome attempts to download a file called downloadhandler.ashx The code for the handler is

<%@ 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;
    }
}



}

The handler receives its information from this piece of code

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));
}

which is used in this method

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

Any help in getting this download functionality to work in Chrome would be greatly appreciated.

Try removing "inline" from the Content-Disposition header as "inline" & "attachment" aren't supposed to be used together:

context.Response.AddHeader("Content-Disposition", "attachment; filename=\""
    + fileInfo.Name + "\"");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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