Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download file with Swagger UI

I have rest controller which is returning HttpResponseMessage with Stream file as a content, something like this:

public class MyController : ApiController
{
    public HttpResponseMessage GetFile(string id)
    {
        try { 
            var stream = fileSystemUtils.GetFileStream(filePath); //Get Stream
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = stream;
            return response;
        }
        catch (FileNotFoundException)
        {
            return new HttpResponseMessage(HttpStatusCode.NotFound);
        }
    }
}

When i call this method by ULR in browser everything is ok and i can download this file. Now i would like to download it using Swagger UI. Is some easy way to do this?

like image 764
lukhol Avatar asked May 22 '17 17:05

lukhol


2 Answers

In case someone else is looking for this, I did the following:

public class FileOperation : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (operation.OperationId.ToLower() == "apifileget")
        {
            operation.Produces = new[] { "application/octet-stream" };
            operation.Responses["200"].Schema = new Schema { Type = "file", Description = "Download file"};
        }
    }
}

//In the startup...
services.AddSwaggerGen(c =>
{
    //missing code...
    c.OperationFilter<FileOperation>();
});
like image 96
Bianca Avatar answered Sep 18 '22 22:09

Bianca


This is what worked for me (.Net Core 2.2 and Swashbuckle 4.0.1):

[Route("api/[controller]")]
[ApiController]
public class DownloadController : ControllerBase
{
    [HttpGet("{name}")]
    [ProducesResponseType(typeof(byte[]), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(BadRequestObjectResult), 400)]
    public async Task<IActionResult> GetFile(string fileName)
    {
        var filePath = $"files/{fileName}"; // get file full path based on file name
        if (!System.IO.File.Exists(filePath))
        {
            return BadRequest();
        }
        return File(await System.IO.File.ReadAllBytesAsync(filePath), "application/octet-stream", fileName);
    }
}
like image 33
Marcello Avatar answered Sep 21 '22 22:09

Marcello