Hi @Pratham Jain ,
I need to implement download file functionality where user will be able to download file from URL in downloads folder.
To download file from the file folder (in the wwwroot
folder, if the file folder doesn't in the wwwroot folder, refer to this link), you can get the file path via the IWebHostEnvironment, then read the file content and return a File object to the client.
[Route("api/[controller]")]
[ApiController]
public class ToDoController : ControllerBase
{
private readonly IWebHostEnvironment environment;
public ToDoController(IWebHostEnvironment hostEnvironment)
{
environment = hostEnvironment;
}
[HttpGet("download")]
public IActionResult Download()
{
var filepath = Path.Combine(environment.WebRootPath, "images", "Image1.png");
return File(System.IO.File.ReadAllBytes(filepath), "image/png", System.IO.Path.GetFileName(filepath));
}
Then, in the Index view page, we can add a hyperlink to call this API method and download file:
<a href='~/api/Todo/download' download>Download File From Folder</a>
To download file from URL, you can use HttpClient or IHttpClientFactory, refer to the following code:
Create a DownloadExtention.cs :
public static class DownloadExtention
{
public static async Task<byte[]?> GetUrlContent(string url)
{
using (var client = new HttpClient())
using (var result = await client.GetAsync(url))
return result.IsSuccessStatusCode ? await result.Content.ReadAsByteArrayAsync() : null;
}
}
Then in the API method, create a method as below:
[HttpGet("downloadfromurl")]
public IActionResult DownloadFromUrl(string url)
{
var result = DownloadExtention.GetUrlContent(url);
if (result != null)
{
return File(result.Result, "image/png", "test.jpg");
}
return Ok("file is not exist");
}
Then, add the download hyperlink:
<a href='~/api/Todo/downloadfromurl?url=https://www.learningcontainer.com/wp-content/uploads/2020/07/Large-Sample-Image-download-for-Testing.jpg' download>Download File</a>
The output as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion