How to encode the filename parameter of Content-Disposition header in HTTP?

前端 未结 18 1764
北荒
北荒 2020-11-21 06:15

Web applications that want to force a resource to be downloaded rather than directly rendered in a Web browser issue a Content-Disposition hea

18条回答
  •  日久生厌
    2020-11-21 07:12

    In ASP.NET Web API, I url encode the filename:

    public static class HttpRequestMessageExtensions
    {
        public static HttpResponseMessage CreateFileResponse(this HttpRequestMessage request, byte[] data, string filename, string mediaType)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            var stream = new MemoryStream(data);
            stream.Position = 0;
    
            response.Content = new StreamContent(stream);
    
            response.Content.Headers.ContentType = 
                new MediaTypeHeaderValue(mediaType);
    
            // URL-Encode filename
            // Fixes behavior in IE, that filenames with non US-ASCII characters
            // stay correct (not "_utf-8_.......=_=").
            var encodedFilename = HttpUtility.UrlEncode(filename, Encoding.UTF8);
    
            response.Content.Headers.ContentDisposition =
                new ContentDispositionHeaderValue("attachment") { FileName = encodedFilename };
            return response;
        }
    }
    

    IE 9 Not fixed
    IE 9 Fixed

提交回复
热议问题