.net core API 返回文件
https://stackoverflow.com/questions/42460198/return-file-in-asp-net-core-web-api1: Return FileStreamResult[HttpGet("get-file-stream/{id}"]public async Task<FileStreamResult> DownloadAsync(string
·
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/<DownLoadController>
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/<DownLoadController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<DownLoadController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)