.net core API 返回文件

https://stackoverflow.com/questions/42460198/return-file-in-asp-net-core-web-api
1: Return FileStreamResult

[HttpGet("get-file-stream/{id}"]
public async Task<FileStreamResult> DownloadAsync(string id)
{
    var fileName="myfileName.txt";
    var mimeType="application/octet-stream"; 
    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/octet-stream"; 
    byte[] fileBytes = await GetFileBytesById(id);

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

demo

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SignalRAPI.Hubs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace SignalRAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DownLoadController : ControllerBase
    {
        private readonly IHubContext<ChatHub> _HubContext;


        public DownLoadController(IHubContext<ChatHub> HubContext)
        {
            _HubContext = HubContext;
        }

        // 根据文件名下载文件
        [HttpGet]

        public async Task<IActionResult> DownloadfromBytes(string filename)
        {
            byte[] byteArr = await System.IO.File.ReadAllBytesAsync(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename));
            string mimeType = "application/octet-stream";
            return new FileContentResult(byteArr, mimeType)
            {
                FileDownloadName = filename
            };
        }


        // POST api/
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api//5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api//5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

你可能感兴趣的:(.netCore,.netcore,microsoft)