如何从HTTPResponseMessage下载文件

时间:2014-11-27 18:30:11

标签: asp.net-mvc

我在我的网站上添加了一个链接来下载图像。当我点击链接时,我希望下载自动启动。

目前,当我点击链接时,我收到了回复消息:示例:

StatusCode:200,ReasonPhrase:'OK',版本:1.1,内容:System.Net.Http.PushStreamContent,标题:{Content-Type:application / octet-stream Content-Disposition:attachment; filename = 895621d7-57a4-47a5-8dc5-ae36a2623826Banneraaaaaaaa.jpg}

如何修改以下代码以自动开始下载。我想我可能会回错类型:

这是我的代码:

public HttpResponseMessage DownloadImageFile(string filepath)
        {
            filepath = "https://mysite.com/" + filepath;

            try
            {
                var response = new HttpResponseMessage();
                response.Content = new PushStreamContent((Stream outputStream, HttpContent content, TransportContext context) =>
                {
                    try
                    {
                        DownloadFile(filepath, outputStream);
                    }
                    finally
                    {
                        outputStream.Close();
                    }
                });

                response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(filepath);

                return response;


            }
            catch (Exception ex)
            {

            }

            return null;
        }

        public void DownloadFile(string file, Stream response)
        {
            var bufferSize = 1024 * 1024;

            using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                var buffer = new byte[bufferSize];
                var bytesRead = 0;
                while ((bytesRead = stream.Read(buffer, 0, bufferSize)) > 0)
                {
                    response.Write(buffer, 0, bytesRead);
                }
                response.Flush();
            }
        }

    }

1 个答案:

答案 0 :(得分:2)

您应该使用Controller.File重载之一。 File()帮助器方法提供对返回文件内容的支持。 MediaTypeNames类可用于获取特定文件扩展名的MIME类型。

例如:

    public FileResult Download(string fileNameWithPath)
    {
        // Option 1 - Native support for file read
        return File(fileNameWithPath, System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(fileNameWithPath));

        // Option 2 - Read byte array and pass to file object
        //byte[] fileBytes = System.IO.File.ReadAllBytes(fileName); return
        //File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet,
        //fileName);
    }