从Internet Explorer

时间:2016-03-18 07:58:53

标签: c# asp.net-mvc asp.net-mvc-3

我有一个使用链接设置的web应用程序,当按下此链接时,将下载一个文件。文件位置现在我在我自己的硬盘上。当我从谷歌浏览器下载文件时,它可以工作,但是当我使用IE时,我会得到一个奇怪的乱码文件名。这是我的代码:

[HttpGet]
public HttpResponseMessage GetFile(string filename, string environment)
{
    _requestLogger.LogRequest(Request);

    var validateResult = new InputValidator().ValidateInput(filename);
    if (!validateResult.IsValid)
    {
        return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = validateResult.ErrorMessage };
    }

    filename = SanitizeFileName(filename);

    var filePath = _settings.ResolveFilePath(environment, filename);

    if (!File.Exists(filePath))
    {
        return new HttpResponseMessage(HttpStatusCode.NoContent);
    }

    //Get file
    var stream = new FileStream(filePath, FileMode.Open);

    //Create result
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    //Add content to result
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
} 

以下是指向奇怪的filename

图像的链接

我似乎无法弄清楚为什么会这样。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

尝试添加filenamecontent-length标题,如下所示:

result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
        FileName = fileName.ToString()
};
response.Content.Headers.ContentLength=stream.Length.ToString();

答案 1 :(得分:1)

我想出了我必须做的事情。我创建了这个方法,它解决了我的问题。

public static void AddProperFileNameHeadersIfIE(HttpContextBase httpContext, string fileName)
{
    var browser = httpContext.Request.Browser;

    if (browser != null && browser.Browser.Equals("ie", StringComparison.OrdinalIgnoreCase))
    {
        httpContext.Response.AppendHeader("Content-Disposition", "attachment; filename*=UTF-8''" + HttpUtility.UrlPathEncode(fileName) + "\"");
    }
    else
    {
        httpContext.Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlPathEncode(fileName) + "\"");
    }
}