MVC - 如何从 url 请求和保存 pdf 文件

bar*_*rak 1 .net c# api asp.net-mvc

我需要编写一个包含 3 个部分的 api:

  1. 从 pdf url 获取 pdf 文件。
  2. 转换pdf。
  3. 返回转换后的pdf文件。

我已经完成了第 2 部分和第 3 部分,剩下的就是从 url 获取 pdf 并将其复制/下载到我的 mvc web api。

这是测试的html代码:

< script >
  $('#btnSendRequest').on('click', function() {
    $.ajax({
      type: "POST",
      url: "/Convertor/Html",
      data: {
        strUrl: "http://make-sense.co.il/kb/avcp-script-installation.pdf"
      },
      success: function(data) {
        return true;
      },
    });
  }); < /script>
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
  <title>tester</title>
</head>

<body>
  <h1>tester html</h1>
  <div>
    <input id="btnSendRequest" type="button" value="SendHttpRequest" />

  </div>
Run Code Online (Sandbox Code Playgroud)

我的 ActionResult 函数: "convertor/html" ,从网页中获取 url 字符串。我需要的是当我单击按钮时,pdf 文件将自动下载到我的服务器。

public ActionResult Html(string strUrl) 
    {
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

任何人都知道如何做到这一点?我还在某处阅读了一些名为 base64 编码的内容,这可能也是解决方案,但我以前从未使用过它。

提前致谢。

Ahs*_*san 5

您可能正在寻找的是 .NET 上的 WebClient,请参阅以下示例,我只是从在线示例中获取它,请参阅此处获取完整文章。

using System;
using System.Net;
using System.IO;

class Program
{
    static void Main()
    {
    using (WebClient client = new WebClient())
    {

        // Download data.
        byte[] arr = client.DownloadData("http://url-to-your-pdf-file.com/file1");

        File.WriteAllBytes(path_to_your_app_data_folder, arr)

    }
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要通过将 byte[] 保存为某个文件来进行进一步处理。上面的示例代码用于控制台应用程序,但同样可以在您的 mvc 控制器中实现。