简体   繁体   中英

.NET Core WebAPI - Allow user to download file

What I want to do is that when the web client calls the endpoint, the browser then download the file. Basically, just a download file capability. How would I achieve that?

On my API controller, I have tried these 2 functions, and none of them are prompting the browser to download the file. I tested them on 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);
    }

Or this will not work if using API only? Do I need to test this using a client side application? The web application is on ASP.NET MVC.

If there is any tutorial to allow user to download file in .NET Core, please give them to me. I have Googled a few and none of them are working (or my understanding is totally wrong).

Just to be clear as you haven't mentioned what kind of call you are making from frontend

I'm assuming that you are doing "form post". You can not send ajax request to download file due to limitation of javascript.

Here the code for downloading file.

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中下载文件

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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