c# - MVC - 如何从 URL 请求并保存 pdf 文件

标签 c# .net asp.net-mvc api

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

  1. 从 pdf 网址获取 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>
<!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>

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

public ActionResult Html(string strUrl) 
    {
        return View();
    }

有人知道如何做到这一点吗? 我还在某处读到过一种叫做 base64 编码的东西,这可能也是解决方案,但我以前从未使用过它。

提前致谢。

最佳答案

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

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)

    }
    }
}

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

关于c# - MVC - 如何从 URL 请求并保存 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38036534/

相关文章:

c# - 可以将代码从 Web 表单传递到 View 吗? (C#)

c# - SharePoint 错误 : Web application at xxxx could not be found

c# - 使用 Fluent NHibernate 自动映射字典时,不考虑元素列长度

c# - Reactive 框架是否可用于 .NET Framework 3.5?

jquery数据表服务器端分页mvc与动态列

ajax - 将 antiforgerytoken 放在 _Layout.cshtml 中是否有意义?

c# - 从显示的 dataGridView 中删除一行?

c# - ASP MVC - 将 ViewModel 对象转换为另一种类型

c# - 使用 Protocol Buffer 模拟泛型

c# - 在 ASP .NET Core 模型的构造函数中使用 AutoMapper