What is the correct way to download a file via the NSwag Code Generator (angular 2 typescript)

后端 未结 4 1791
盖世英雄少女心
盖世英雄少女心 2021-02-13 16:50

I try to download a file via an angular 2 typescript client. The link generated in Swagger UI works fine, but the generated typescript client does not.

The controller lo

4条回答
  •  不知归路
    2021-02-13 17:54

    In the API, Required Nuget packages:

    1. Microsoft.AspNetCore.StaticFiles // To determine MimeType
    2. NSwag.Annotations // To map the return type of API with Angular Service Generated by NSwag
    

    Search for the pacakges in Nuget and install them.

    Then In Startup.cs,

    services.AddSwaggerGen(options =>
    {
        // Swagger Configurations
        options.MapType(() => new Schema
        {
            Type = "file"
        });
    });
    

    Now add a method to get the MimeType of file

    private string GetMimeType(string fileName)
    {
        var provider = new FileExtensionContentTypeProvider();
        string contentType;
        if (!provider.TryGetContentType(fileName, out contentType))
        {
            contentType = "application/octet-stream";
        }
        return contentType;
    } 
    

    Now Add a method to download file

    [SwaggerResponse(200, typeof(FileContentResult))]
    [ProducesResponseType(typeof(FileContentResult), 200)]
    public FileContentResult DownloadDocument(string fileName)
    { 
        // _environment => IHostingEnvironment Instance
        var filepath = Path.Combine($"{this._environment.WebRootPath}\\path-to\\filename}");
    
        var mimeType = this.GetMimeType(filename);
    
        // Checks if file exists 
        var fileBytes = File.ReadAllBytes(filepath);
        return new FileContentResult(fileBytes, mimeType)
        {
            FileDownloadName = filename
        };
    }
    

    Now the downloadFile method in angular service generated by NSwag will return Observable. To Consume the service, first install file-saver using npm i file-saver. Then import it in component
    import { saveAs } from 'file-saver';

    downloadDocument = (filename: string): void => {
        this._service.downloadDocument(filename).subscribe((res) => {
          saveAs(res.data, 'filename');
        });
      };
    

    This will download file.

提交回复
热议问题