0

I'm trying to download a file using IDownstreamApi I've tried the following code

    var file = await downstreamApi.GetForAppAsync<Stream>(Definitions.FileshareApi, options =>
    {
        options.RelativePath = $"{ApiPaths.FileDownload}{sourceUri}";
    }, cancellationToken: cancellationToken);
    if(file != null)
    {
        var target = new FileStream(targetFilePath, FileMode.Create);
        file.CopyTo(target);
        return true;
    }

but I get the following exception

System.Text.Json.JsonException: 'The JSON value could not be converted to System.IO.Stream. Path: $ | LineNumber: 0 |

Is it possible to download a file using the IDownstreamApi. If how do you use it to do this.

Mark
  • 2,392
  • 4
  • 21
  • 42

2 Answers2

0

This method is deserializing received JSON data into this type. downstreamApi.GetForAppAsync<SomeType>(...) will just:

  1. Using GET method receive data from url
  2. Treat it as JSON content
  3. Try to deserialize this content into SomeType

So basically your code is trying to deserialize it to Stream object, which is not the same as putting content into stream.

GroM
  • 1
  • I already understood that, what I'm trying to figure out is if it's possible to use the downstreamApi to download the file or if it's designed to only deserialize the response into a strongly typed object – Mark Jul 19 '23 at 09:22
0

Figured it out myself:

    var response = await downstreamApi.CallApiForAppAsync(Definitions.FileshareApi, options =>
    {
        options.HttpMethod = HttpMethod.Get;
        options.RelativePath = $"{ApiPaths.FileDownload}{sourceUri}";
    }, cancellationToken: cancellationToken);
    if (response != null)
    {
        using Stream output = File.OpenWrite(Path.Combine(targetFilePath, targetFileName));
        response.Content.CopyTo(output, null, cancellationToken);
    }
Mark
  • 2,392
  • 4
  • 21
  • 42