3

I am trying to save a file to the client's machine. I want to require the client to pick the location of the download.

I have endpoint of the REST service which returns the file to be downloaded. I am trying to set up the code to download the file thats returned from the service with save as dialog.

 var Url = "https://randomaddresss/v5/invoices/{" + InvoicesId + "}/getpdfbyid"; HttpResponse response = HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/pdf"; response.AddHeader("Content-Disposition", "attachment; filename=" + InvoicesId + ".pdf;"); response.TransmitFile(Url); response.Flush(); response.End(); 

The error thats returned is on the line response.TransmitFile(Url); :

'https:/randomaddresss/v5/invoices/2131231231231312/getpdfbyid' is not a valid virtual path.

3
  • I'm assuming your application is a website? TransmitFile is to transmit a file to the client from your servers's filesystem, not from an url Commented Aug 13, 2020 at 13:27
  • Yes, that is right, my application is a website. Commented Aug 13, 2020 at 13:28
  • 1
    I would say you could load the file from the rest api in memory and pass the stream to your client Commented Aug 13, 2020 at 13:29

2 Answers 2

4

JS:

function downloadPdfInvoice(iId) { $.ajax({ url: '/api/DownloadInvoice?Invoice=' + iId, type: 'get', success: function (response, status) { if (response) { var link = document.createElement('a'); link.href = "data:application/octet-stream;base64," + response.Data; link.target = '_blank'; link.download = iId + '.pdf'; link.click(); } }, }); 

}

CS:

 [HttpGet] public ApiResponse DownloadInvoiceAsync(string InvoicesId) { try { String Url = "https://test/{" + InvoicesId + "}/getpdfinvoice"; HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(Url); var resp = fileReq.GetResponse(); Stream input = resp.GetResponseStream(); byte[] data = input.ReadAsBytes(); return new ApiResponse(true, "Downloadet til skrivebordet.", data); } catch (Exception ex) { Logger.Warn(MethodBase.GetCurrentMethod().DeclaringType, string.Format("DownloadInvoice Exception {0}", ex.Message)); throw ex; } } 
Sign up to request clarification or add additional context in comments.

Comments

2

HttpResponse.TransmitFile expects a file path, not a URL.

You will need to download the file first, then write to the response stream.

Here's an example using HttpClient:

using var invoiceResponse = await httpClient.GetAsync(Url); using var invoiceStream = await invoiceResponse.Content.ReadAsStreamAsync(); invoiceStream.CopyTo(response.OutputStream); response.ContentType = "application/pdf"; response.AddHeader("Content-Disposition", "attachment; filename=" + InvoicesId + ".pdf;"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.