Return 文件在 ASP.Net 核心网站 API

Return file in ASP.Net Core Web API

问题

我想 return 我的 ASP.Net 网络 API 控制器中的一个文件,但是我所有的方法 return HttpResponseMessage 作为 JSON.

到目前为止的代码

public async Task<HttpResponseMessage> DownloadAsync(string id)
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent({{__insert_stream_here__}});
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    return response;
}

当我在浏览器中调用此端点时,Web API return 将 HttpResponseMessage 设置为 JSON,HTTP 内容 Header 设置为application/json.

如果这是 ASP.net-Core,那么您正在混合 Web API 版本。将操作 return 派生为 IActionResult,因为在您当前的代码中,框架将 HttpResponseMessage 视为模型。

[Route("api/[controller]")]
public class DownloadController : Controller {
    //GET api/download/12345abc
    [HttpGet("{id}")]
    public async Task<IActionResult> Download(string id) {
        Stream stream = await {{__get_stream_based_on_id_here__}}

        if(stream == null)
            return NotFound(); // returns a NotFoundResult with Status404NotFound response.

        return File(stream, "application/octet-stream"); // returns a FileStreamResult
    }    
}

注:

The framework will dispose of the stream used in this case when the response is completed. If a using statement is used, the stream will be disposed before the response has been sent and result in an exception or corrupt response.

您可以 return FileResult 使用此方法:

1: Return FileStreamResult

    [HttpGet("get-file-stream/{id}"]
    public async Task<FileStreamResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        Stream stream = await GetFileStreamById(id);

        return new FileStreamResult(stream, mimeType)
        {
            FileDownloadName = fileName
        };
    }

2: Return FileContentResult

    [HttpGet("get-file-content/{id}"]
    public async Task<FileContentResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        byte[] fileBytes = await GetFileBytesById(id);

        return new FileContentResult(fileBytes, mimeType)
        {
            FileDownloadName = fileName
        };
    }

这是一个流式传输文件的简单示例:

using System.IO;
using Microsoft.AspNetCore.Mvc;
[HttpGet("{id}")]
public async Task<FileStreamResult> Download(int id)
{
    var path = "<Get the file path using the ID>";
    var stream = File.OpenRead(path);
    return new FileStreamResult(stream, "application/octet-stream");
}

注:

请务必使用 Microsoft.AspNetCore.Mvc 中的 FileStreamResultSystem.Web.Mvc 中的 而不是

ASP.NET 5 网络 API & Angular 12

您可以 return 来自服务器的 FileContentResult 对象 (Blob)。它不会自动下载。您可以在前端应用程序中以编程方式创建锚标记,并将 href 属性 设置为通过以下方法从 Blob 创建的对象 URL。现在单击锚点将下载文件。您也可以通过将 'download' 属性设置为锚点来设置文件名。

downloadFile(path: string): Observable<any> {
        return this._httpClient.post(`${environment.ApiRoot}/accountVerification/downloadFile`, { path: path }, {
            observe: 'response',
            responseType: 'blob'
        });
    }

saveFile(path: string, fileName: string): void {
            this._accountApprovalsService.downloadFile(path).pipe(
                take(1)
            ).subscribe((resp) => {
                let downloadLink = document.createElement('a');
                downloadLink.href = window.URL.createObjectURL(resp.body);
                downloadLink.setAttribute('download', fileName);
                document.body.appendChild(downloadLink);
                downloadLink.click();
                downloadLink.remove();
            });
            
        }

后端

[HttpPost]
[Authorize(Roles = "SystemAdmin, SystemUser")]
public async Task<IActionResult> DownloadFile(FilePath model)
{
    if (ModelState.IsValid)
    {
        try
        {
            var fileName = System.IO.Path.GetFileName(model.Path);
            var content = await System.IO.File.ReadAllBytesAsync(model.Path);
            new FileExtensionContentTypeProvider()
                .TryGetContentType(fileName, out string contentType);
            return File(content, contentType, fileName);
        }
        catch
        {
            return BadRequest();
        }
    }

    return BadRequest();

}

以下是在 .NET Core Web returning 文件(例如图像文件)的基本示例 API:

<img src="@Url.Action("RenderImage", new { id = id})" alt="No Image found" />

下面是 returning 文件从控制器查看的代码。以下是 return 文件的操作方法:

    [Route("api/[controller]")]
    public class DownloadController : Controller
    {
        //GET api/download/123
        [HttpGet]
        public async Task<IActionResult> RenderImage(string userId)
        {
            //get Image file using _fileservice from db
            var result = await _fileService.getFile(userId);

            if (result.byteStream == null)
                return NotFound();

            return File(result.byteStream, result.ContentType, result.FileName);
        }
    }

注:

Our file should be first converted into byte[] and then saved in database as varbinary(max) in order to retrieve.

FileStreamResult 适合我。并且 File 不是 IActionResult。我不知道它是如何工作的。