如何将文件从 URL 下载到服务器文件夹
How to download a file from an URL to a server folder
我正在开发 ASP.NET 核心网络应用程序,并且我正在使用 Razor Pages。
我的应用程序中显示了一些 URL,当我单击其中一个时,我想将与该 URL 对应的文件下载到应用程序所在服务器上的文件夹中存储,而不是在客户端。
这很重要,因为该文件需要由某些其他第三方应用程序在服务器端进行处理。
URL 和其他元数据来自数据库,我创建了一个数据库上下文来加载它们。我制作了一个 CSS HTML 文件并以表格形式显示信息。当我单击一个按钮时,我 post 将 URL 传递给方法处理程序。
我在方法中收到了 URL,但我不知道如何在服务器上下载该文件,而不是先在客户端下载它然后 saving/uploading 到服务器。我怎样才能做到这一点?
可以使用System.Net.WebClient
using (WebClient Client = new WebClient ())
{
Client.DownloadFile (
// Param1 = Link of file
new System.Uri("Given URL"),
// Param2 = Path to save
"On SERVER PATH"
);
}
启动 .NET 6 WebRequest
、WebClient
和 ServicePoint
类 are deprecated.
要使用推荐的 HttpClient
下载文件,您需要这样做:
// using System.Net.Http;
// using System.IO;
var httpClient = new HttpClient();
var responseStream = await httpClient.GetStreamAsync(requestUrl);
using var fileStream = new FileStream(localFilePath, FileMode.Create);
responseStream.CopyTo(fileStream);
记住不要使用using
,并且不要在每次使用后处理HttpClient
实例。更多上下文 here and here.
获取HttpClient
实例的recommended way是从IHttpClientFactory
获取实例。如果您使用 HttpClientFactory
获得 HttpClient
实例,您可以在每次使用后处理 HttpClient
实例。
我正在开发 ASP.NET 核心网络应用程序,并且我正在使用 Razor Pages。
我的应用程序中显示了一些 URL,当我单击其中一个时,我想将与该 URL 对应的文件下载到应用程序所在服务器上的文件夹中存储,而不是在客户端。
这很重要,因为该文件需要由某些其他第三方应用程序在服务器端进行处理。
URL 和其他元数据来自数据库,我创建了一个数据库上下文来加载它们。我制作了一个 CSS HTML 文件并以表格形式显示信息。当我单击一个按钮时,我 post 将 URL 传递给方法处理程序。
我在方法中收到了 URL,但我不知道如何在服务器上下载该文件,而不是先在客户端下载它然后 saving/uploading 到服务器。我怎样才能做到这一点?
可以使用System.Net.WebClient
using (WebClient Client = new WebClient ())
{
Client.DownloadFile (
// Param1 = Link of file
new System.Uri("Given URL"),
// Param2 = Path to save
"On SERVER PATH"
);
}
启动 .NET 6 WebRequest
、WebClient
和 ServicePoint
类 are deprecated.
要使用推荐的 HttpClient
下载文件,您需要这样做:
// using System.Net.Http;
// using System.IO;
var httpClient = new HttpClient();
var responseStream = await httpClient.GetStreamAsync(requestUrl);
using var fileStream = new FileStream(localFilePath, FileMode.Create);
responseStream.CopyTo(fileStream);
记住不要使用using
,并且不要在每次使用后处理HttpClient
实例。更多上下文 here and here.
获取HttpClient
实例的recommended way是从IHttpClientFactory
获取实例。如果您使用 HttpClientFactory
获得 HttpClient
实例,您可以在每次使用后处理 HttpClient
实例。