【问题标题】:I want to download file using direct link without file read我想使用直接链接下载文件而不读取文件
【发布时间】:2020-10-13 11:28:42
【问题描述】:

我正在使用此代码,但通过此代码发生读取文件。我想使用此直接链接下载此文件,无需读取字节。如果有其他方法可以做到这一点,请提出它。 不使用WebClient还有其他方法吗以及不保存路径怎么办

        System.Net.WebClient webClient = new System.Net.WebClient();
        string url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
        byte[] bytes = webClient.DownloadData(url);
        string filename = Path.GetFileName(url);
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
        Response.BinaryWrite(bytes);
        Response.End();

【问题讨论】:

  • 使用HttpClient代替WebClient:"我们不建议您使用WebClient类进行新的开发。而是使用System.Net.Http.HttpClient类。" - WebClient Remarks Section
  • 我同意 HttpClient 更好,尤其是如果您可以正确使用 async/await,但 WebClient 确实有一个 DownloadFile 方法。
  • ^^ WebClient.DownloadFile(string,string) "将具有指定URI的资源下载到本地文件。"
  • 不使用WebClient有没有其他方法

标签: c# asp.net arrays iis download


【解决方案1】:

不使用WebClient有没有其他方法

当然。只需获取一个 Stream 即可将其复制到 Http Response 流中。比如:

        System.Net.WebClient webClient = new System.Net.WebClient();
        string url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
        Stream data = webClient.OpenRead(url);
        string filename = Path.GetFileName(url);
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
        data.CopyTo(Response.OutputStream);
        Response.End();

【讨论】:

  • 可以直接从链接下载文件,无需读取文件
  • 这是个问题吗?
【解决方案2】:

你可以试试blow code:

string k = "http://sub.domain.com/uploads/test.pdf";
        Response.ContentType = "Application/pdf";
        Response.AppendHeader("Content-Disposition", "attachment; filename=Test_PDF.pdf");

        WebClient wc = new WebClient();
        byte[] myDataBuffer = wc.DownloadData(k);
        Response.BinaryWrite(myDataBuffer);
        Response.End();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 2017-09-11
    • 2017-08-26
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多