Jan*_*use 98 c# .net-core asp.net-core asp.net-core-webapi
我想在我的ASP.Net Web API Controller中返回一个文件,但我的所有方法都返回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;
}
Run Code Online (Sandbox Code Playgroud)
当我在浏览器中调用此端点时,Web API会返回设置HttpResponseMessage
为HTTP Content Header 的as JSON application/json
.
Nko*_*osi 182
如果这是ASP.net-Core,那么您正在混合Web API版本.让操作返回派生,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
}
}
Run Code Online (Sandbox Code Playgroud)
Ham*_*aei 31
您可以使用以下方法返回 FileResult:
1:返回 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
};
}
Run Code Online (Sandbox Code Playgroud)
2:返回文件内容结果
[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
};
}
Run Code Online (Sandbox Code Playgroud)
gpr*_*and 21
这是流式传输文件的简单示例:
using System.IO;
using Microsoft.AspNetCore.Mvc;
Run Code Online (Sandbox Code Playgroud)
[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");
}
Run Code Online (Sandbox Code Playgroud)
笔记:
一定要使用FileStreamResult
fromMicrosoft.AspNetCore.Mvc
而不是from System.Web.Mvc
。
小智 8
ASP.NET 5 WEB API 和 Angular 12
您可以从服务器返回 FileContentResult 对象 (Blob)。它不会自动下载。您可以通过编程方式在前端应用程序中创建锚标记,并将 href 属性设置为通过以下方法从 Blob 创建的对象 URL。现在单击锚点将下载该文件。您也可以通过将“下载”属性设置为锚点来设置文件名。
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();
});
}
Run Code Online (Sandbox Code Playgroud)
后端
[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();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
90641 次 |
最近记录: |