【问题标题】:WebAPI File DownloadWebAPI 文件下载
【发布时间】:2019-01-11 14:53:46
【问题描述】:

我需要创建一个下载文件的 WebAPI 方法。该文件正在正确下载,但下载似乎仍然停留在客户端浏览器中几乎 100% 的速度(即,尽管文件已经下载并且可以打开,但它不会终止)。在终止之前保持这种状态几分钟。问题可能是什么?以下是一些复制我的问题的测试代码

[HttpGet]
public HttpResponseMessage GetFile()
{
    string fileName = @"c:\temp\test.zip";

    MemoryStream responseStream = new MemoryStream();
    using (FileStream source = File.Open(fileName, FileMode.Open))
        source.CopyTo(responseStream);

    HttpResponseMessage response = new HttpResponseMessage();
    response.Content = new StreamContent(responseStream);
    response.StatusCode = HttpStatusCode.OK;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue(ContentTypeHelper.Instance.GetFileContentType(fileName));
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = fileName;
    response.Content.Headers.ContentLength = responseStream.Length;
    return response;
}

【问题讨论】:

  • Remove response.Content.Headers.ContentLength = responseStream.Length; StreamContent 将根据包含的流进行设置。
  • 我尝试添加该行以查看它是否可以解决我的问题,但它没有。在我没有包含它之前,不幸的是它仍然无法正常工作。

标签: asp.net-web-api asp.net-web-api2 httpresponsemessage


【解决方案1】:

看来您需要在复制后倒带 MemoryStream:

MemoryStream responseStream = new MemoryStream();
using (FileStream source = File.Open(fileName, FileMode.Open))
    source.CopyTo(responseStream);
responseStream.Seek(0, SeekOrigin.Begin);

【讨论】:

    猜你喜欢
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 2020-12-02
    • 2017-06-16
    相关资源
    最近更新 更多