Cómo descargar un archivo en Angular .NET
En este artículo, le mostraré cómo descargar un archivo en un proyecto Angular con una API web .NET
.NET
Necesitas crear un controlador, por ejemplo DownloadController, con una API DownloadFile de tipo HttpGet. Si lo deseas puedes enviar el nombre del archivo a descargar como parámetro para esta API.
Primero, transforme su archivo en una matriz de bytes o mediante un memoryStream, luego devuélvalo en un FileContentResult pasando su matriz de bytes, el tipo "application/octet-stream" y el nombre de su archivo.
[Route("api/[controller]")]
public class DownloadController : Controller
{
[HttpGet]
public async Task<IActionResult> DownloadFile()
{
//Set your file path here
var path = Path.Combine(Directory.GetCurrentDirectory(), "Ressources", "Example.docx");
//Check if the file exists
if (!System.IO.File.Exists(path))
return NotFound();
//Get Bytes array of your file, you can also to do a MemoryStream
Byte[] bytes = await System.IO.File.ReadAllBytesAsync(path);
//Return your FileContentResult
return File(bytes, "application/octet-stream", "Example.docx");
}
}
EN Angular
En su servicio, cree una función para llamar a la API .Net, debe especificar 'blob' para el tipo de respuesta de esta manera:
downloadFile() {
return this.http.get('http://localhost:5000/api/download/', { responseType: 'blob' });
}
En Angular, la mejor biblioteca para descargar archivos es file-saver, que puedes instalar con:
npm i file-saver
Escriba una función en su componente para llamar a su servicio.
download() {
this.fileService.downloadFile()
.subscribe(data => saveAs(data, 'Example.docx'));
}
A continuación, agregue la importación para utilizar el protector de archivos.
import { saveAs } from "file-saver";
Y funciona.