繁体   English   中英

.NET Core WebAPI - 允许用户下载文件

[英].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");

        }
    }
}

如何在asp.net core中下载文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM