Como baixar um ZipFile de um webapi dotnet core?
Estou tentando fazer o download de um arquivo zip de uma ação de API da web do dotnet core, mas não consigo fazê-lo funcionar. Tentei chamar a ação via POSTMAN e meu Aurelia Http Fetch Client.
Eu sou capaz de criar o ZipFile como eu quero e armazená-lo no sistema, mas não consigo corrigi-lo, para que ele retorne o zipfile pela API.
Caso de uso: o usuário seleciona algumas coleções de imagens e clica no botão de download. Os IDs das coleções de imagens são enviados para a API e é criado um arquivo zip que contém um diretório para cada coleção de imagens que contém as imagens. Esse arquivo zip é retornado ao usuário para que ele possa armazená-lo em seu sistema.
Qualquer ajuda seria apreciada.
Minha ação do controlador
/// <summary>
/// Downloads a collection of picture collections and their pictures
/// </summary>
/// <param name="ids">The ids of the collections to download</param>
/// <returns></returns>
[HttpPost("download")]
[ProducesResponseType(typeof(void), (int) HttpStatusCode.OK)]
public async Task<IActionResult> Download([FromBody] IEnumerable<int> ids)
{
// Create new zipfile
var zipFile = $"{_ApiSettings.Pictures.AbsolutePath}/collections_download_{Guid.NewGuid().ToString("N").Substring(0,5)}.zip";
using (var repo = new PictureCollectionsRepository())
using (var picturesRepo = new PicturesRepository())
using (var archive = ZipFile.Open(zipFile, ZipArchiveMode.Create))
{
foreach (var id in ids)
{
// Fetch collection and pictures
var collection = await repo.Get(id);
var pictures = await picturesRepo
.GetAll()
.Where(x => x.CollectionId == collection.Id)
.ToListAsync();
// Create collection directory IMPORTANT: the trailing slash
var directory = $"{collection.Number}_{collection.Name}_{collection.Date:yyyy-MM-dd}/";
archive.CreateEntry(directory);
// Add the pictures to the current collection directory
pictures.ForEach(x => archive.CreateEntryFromFile(x.FilePath, $"{directory}/{x.FileName}"));
}
}
// What to do here so it returns the just created zip file?
}
}
Minha aurelia busca a função do cliente:
/**
* Downloads all pictures from the picture collections in the ids array
* @params ids The ids of the picture collections to download
*/
download(ids: Array<number>): Promise<any> {
return this.http.fetch(AppConfiguration.baseUrl + this.controller + 'download', {
method: 'POST',
body: json(ids)
})
}
O que eu tentei
Observe que o que tentei não gera erros, apenas parece não fazer nada.
1) Criando meu próprio FileResult (como costumava fazer com o ASP.NET antigo). Não consigo ver os cabeçalhos sendo usados quando eu o chamo pelo carteiro ou pelo aplicativo.
return new FileResult(zipFile, Path.GetFileName(zipFile), "application/zip");
public class FileResult : IActionResult
{
private readonly string _filePath;
private readonly string _contentType;
private readonly string _fileName;
public FileResult(string filePath, string fileName = "", string contentType = null)
{
if (filePath == null) throw new ArgumentNullException(nameof(filePath));
_filePath = filePath;
_contentType = contentType;
_fileName = fileName;
}
public Task ExecuteResultAsync(ActionContext context)
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(System.IO.File.ReadAllBytes(_filePath))
};
if (!string.IsNullOrEmpty(_fileName))
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = _fileName
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue(_contentType);
return Task.FromResult(response);
}
}
}
2)https://stackoverflow.com/a/34857134/2477872
Faz nada.
HttpContext.Response.ContentType = "application/zip";
var result = new FileContentResult(System.IO.File.ReadAllBytes(zipFile), "application/zip")
{
FileDownloadName = Path.GetFileName(zipFile)
};
return result;
Eu tentei com um arquivo PDF de teste e parecia funcionar com o POSTMAN. Mas quando tento alterá-lo para o arquivo zip (veja acima), ele não faz nada.
HttpContext.Response.ContentType = "application/pdf";
var result = new FileContentResult(System.IO.File.ReadAllBytes("THE PATH/test.pdf"), "application/pdf")
{
FileDownloadName = "test.pdf"
};
return result;