【问题标题】:Download file from REST service in C#从 C# 中的 REST 服务下载文件
【发布时间】:2020-12-03 08:30:07
【问题描述】:

我正在尝试将文件保存到客户端的机器上。我想要求客户端选择下载位置。

我有 REST 服务的端点,它返回要下载的文件。我正在尝试设置代码以使用另存为对话框下载从服务返回的文件。

            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();

返回的错误在response.TransmitFile(Url);这一行:

'https://randomaddresss/v5/invoices/2131231231231312/getpdfbyid' 不是有效的虚拟路径。

【问题讨论】:

  • 我假设您的应用程序是一个网站? TransmitFile 是将文件从服务器的文件系统传输到客户端,而不是从 url
  • 是的,没错,我的应用是一个网站。
  • 我会说你可以从内存中的其余 api 加载文件并将流传递给你的客户端

标签: c# api rest asp.net-web-api


【解决方案1】:

HttpResponse.TransmitFile 需要文件路径,而不是 URL。

您需要先下载文件,然后写入响应流。

这是一个使用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;");

【讨论】:

    【解决方案2】:

    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;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2016-06-11
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 2017-11-16
      • 1970-01-01
      • 2017-11-27
      相关资源
      最近更新 更多