[英].NET Core WebAPI - Allow user to download file
我想要做的是,當 web 客戶端調用端點時,瀏覽器然后下載文件。 基本上,只是一個下載文件的能力。 我將如何實現這一目標?
在我的 API 控制器上,我嘗試了這 2 個函數,但它們都沒有提示瀏覽器下載文件。 我在 Swagger 上測試了它們。
[HttpGet]
public ActionResult Download()
{
var path = @"C:\Users\farid\Desktop";
return PhysicalFile(path, "text/plain", "Test.txt");
}
[HttpGet]
public IActionResult GetBlobDownload()
{
var content = new FileStream(
@"C:\Users\farid\Desktop\Test.txt",
FileMode.Open,
FileAccess.Read,
FileShare.Read);
var contentType = "text/plain";
var fileName = "testfile.txt";
return File(content, contentType, fileName);
}
或者,如果僅使用 API,這將不起作用? 我是否需要使用客戶端應用程序對此進行測試? Web 應用程序位於 ASP.NET MVC 上。
如果有任何教程允許用戶在 .NET Core 中下載文件,請給我。 我在谷歌上搜索了一些,但都沒有工作(或者我的理解完全錯誤)。
只是要清楚,因為您沒有提到您正在從前端撥打什么樣的電話
我假設你正在做“表單發布”。 由於 javascript 的限制,您無法發送 ajax 請求來下載文件。
這里是下載文件的代碼。
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.PlatformAbstractions;
using System.IO;
namespace DeafultAPICoreProject.Controllers
{
[Route("api/values")]
[ApiController]
public class ValuesController : ControllerBase
{
[Route("download")]
public IActionResult DownloadFile()
{
var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, $"TextFile.txt");
var bytes = System.IO.File.ReadAllBytes(filePath);
return File(bytes, "application/octet-stream", "newfile.txt");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.