我需要编写一个包含 3 个部分的 api:
- 从 pdf 网址获取 pdf 文件。
- 转换 PDF。
- 返回转换后的 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/