使用Web API下载文件

huangapple go评论85阅读模式
英文:

Using Web API to download a file

问题

我对Web API模板进行了轻微更改,以使下载工作端点。

[HttpGet(Name = "GetWeatherForecast")]
public FileStream Get()
{
    var path = @"C:\Users\user1\download.msi";
    return new FileStream(path, FileMode.Open, FileAccess.Read);
}

这是一个100MB的下载文件,当我尝试下载文件时,出现了"内存不足"的问题。

英文:

I took the Web API template and made slight change to working endpoint for the download.

[HttpGet(Name = "GetWeatherForecast")]
public FileStream Get()
{
    var path = @"C:\Users\user1\download.msi";
    return new FileStream(path, FileMode.Open, FileAccess.Read);
}

It's a 100mb download and I'm getting Out of memory when I trying download the file.

答案1

得分: 1

要输出一个文件,你应该使用 File 方法:

var f = new FileStream(path, FileMode.Open, FileAccess.Read);
return File(f, "application/octet-stream");

如果你返回一个 FileStream,我猜 ASP.NET 会将其视为 特殊类型,在输出之前尝试对整个对象进行序列化。

英文:

To output a file, you should use the File method:

var f = new FileStream(path, FileMode.Open, FileAccess.Read);
return File(f, "application/octet-stream");

If you return a FileStream, I guess ASP.NET will consider it as special type, attempting to serialize the entire object before outputing it.

huangapple
  • 本文由 发表于 2023年6月19日 07:17:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定