mak*_*chi 5 c# filestream asp.net-core asp.net-core-webapi
我已经搜索了一段时间,虽然它应该很简单,但我就是无法让它工作。根据我见过的例子,这是我到目前为止得到的:
SomeAppService.cs
public async Task<FileStream> Download(long? id)
{
var attachment = await _repository.FirstOrDefaultAsync(x => x.Id == id);
var fileStream = new FileStream($"{attachment.FileName}.{attachment.FileExtension}",
FileMode.Create, FileAccess.Write);
fileStream.Write(attachment.File, 0, attachment.File.Length);
return fileStream;
}
Run Code Online (Sandbox Code Playgroud)
可以注意到,“FileName”、“FileExtension”和“File”(即前述的字节数组)存储在数据库中。附件可以是任何类型的文件,但上传方法中禁止的扩展名除外(未显示)。然后在我的控制器中我有:
SomeController.cs
[AllowAnonymous]
[HttpGet("Download/{id}")]
public async Task<IActionResult> Download(long? id)
{
var fileStream = await appService.Download(id);
return new FileStreamResult(fileStream, "application/octet-stream");
}
Run Code Online (Sandbox Code Playgroud)
然而,当我到达下载端点时,我最终得到一个名为“response”的文件,没有扩展名,大小为 0 字节。
资源:
将 MemoryStream 保存到文件或从文件加载(255 个赞成票的响应让我了解了如何将字节数组转换为文件流,但我不知道这是否有效)
谢谢大家,最后FileContentResult成功了。
它看起来是这样的:
服务
public async Task<Attachment> Download(long? id)
{
return await _repository.FirstOrDefaultAsync(x => x.Id == id);
}
Run Code Online (Sandbox Code Playgroud)
控制器
[AllowAnonymous]
[HttpGet("Download/{id}")]
public async Task<IActionResult> Download(long? id)
{
var attachment = await appService.Download(id);
return new FileContentResult(attachment.File,
MimeTypeMap.GetMimeType(attachment.FileExtension))
{
FileDownloadName = $"{attachment.NomeFile}.{attachment.FileExtension}"
};
}
Run Code Online (Sandbox Code Playgroud)
MimeTypeMap可以在这里找到
| 归档时间: |
|
| 查看次数: |
18381 次 |
| 最近记录: |