Content disposition usage in a React Applications

26 views Asked by At

I have been looking at content-disposition for some time and felt it is interesting and thought of trying out a sample.

I created a HTML file, added an anchor tag in it.

<html>
  <body>
    <a href="http://localhost:portnumber/mysample/file" >Download</a>
  </body>
</html>

I created a web api with below code to return me a file with the needed headers. ( I am not too sure if the code is correct or not. Please correct me if I am doing it wrong. ) I referred the endpoint to the above

[HttpGet]
    [Route("file")]
    public HttpResponseMessage GetFile()
    {
        var stream = new MemoryStream();
        // processing the stream.

        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream.ToArray())
        };
        result.Content.Headers.ContentDisposition =
            new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = "CertificationCard.pdf"
            };
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");

        return result;
    }

Running the above C# code, and requesting it in postman, it returned me the below response

{
"version": {
    "major": 1,
    "minor": 1,
    "build": -1,
    "revision": -1,
    "majorRevision": -1,
    "minorRevision": -1
},
"content": {
    "headers": [
        {
            "Key": "Content-Disposition",
            "Value": [
                "attachment; filename=CertificationCard.pdf"
            ]
        },
        {
            "Key": "Content-Type",
            "Value": [
                "application/octet-stream"
            ]
        }
    ]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"trailingHeaders": [],
"requestMessage": null,
"isSuccessStatusCode": true
 }

After reading about content-disposition, I thought, clicking on the link would have downloaded the file. But it opened the response in browser.

Can someone help me on how to use content disposition. Also, in case, if I am have a SPA application using React or Angular or Vue, we would have authentication headers. How would we pass in authentication headers in this scenario?

I am not sure if I am doing it correctly, as content disposition is pretty new to me.

Any help is highly appreciated.

0

There are 0 answers