locked
How to save PDF file which is sent from Web API? RRS feed

  • Question

  • User600651647 posted

    My code is calling an API and the API is returning a PDF file in pdf format.

    What is the easiest way to extract the PDF file and store it in the local disk?

    Monday, July 2, 2018 9:48 PM

All replies

  • User541108374 posted

    Hi,

    My code is calling an API and the API is returning a PDF file in pdf format.

    It would be handy for next time that you would add the relevant parts of your code. I can only assume you can get the pdf as a stream at the moment from a webrequest call.

    System.IO has all the needed classes available for you to write to disk like Directory and File. 

    Kris.

    Tuesday, July 3, 2018 5:33 AM
  • User36583972 posted


    Hi robinspaul,

    My code is calling an API and the API is returning a PDF file in pdf format.

    What is the easiest way to extract the PDF file and store it in the local disk?

    The following samples describe how to get a file as the response and save it on the local disk.

    Returning File as response to REST Request
    https://www.codeproject.com/articles/1068871/returning-file-stream-as-response-to-rest-request

    How to Return Files From Web API:
    https://www.c-sharpcorner.com/article/sending-files-from-web-api/

    You can use the following code to save the response.Content(Stream) on the local disk.

      using (HttpClient client = new HttpClient())
                    {
                         string url = "api file download address";
                        using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
                        using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
                        {
                            // local address
                            string fileToWriteTo = HttpContext.Current.Server.MapPath("~/uploads")+"test.zip";
                            using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create))
                            {
                                await streamToReadFrom.CopyToAsync(streamToWriteTo);
                            }
                        }
                    }
    

    Besides, If we have any misunderstanding, you can include all necessary code snippets and a detailed description about the issue. This will help us quickly analyze your problem.


    Best Regards,

    Yong Lu

    Tuesday, July 3, 2018 7:28 AM