简体   繁体   中英

How to download a file from an URL to a server folder

I am working on an ASP.NET Core web app and I'm using Razor Pages.

I have some URLs displayed in my app and when I click on one of them, I want to download the file corresponding to that URL on a folder on the server where the application is stored, not on the client.

This is important because the file needs to be processed server-side by some other third-party applications.

The URLs along with other metadata are coming from a database and I created a DB context to load them. I made a CSS HTML file and displayed the information in a form. When I click on a button, I post the URL to a method handler.

I receive the URL in the method but I don't know how to download that file on the server without downloading it first on the client and then saving/uploading it to the server. How can I achieve this?

can use 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"
        );
}

Starting .NET 6 WebRequest , WebClient , and ServicePoint classes are deprecated .

To download a file using the recommended HttpClient instead, you'd do something like this:

// 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);

Remember to not use using , and to not dispose the HttpClient instance after every use. More context here and here .

The recommended way to acquire a HttpClient instance is to get it from IHttpClientFactory . If you get an HttpClient instance using a HttpClientFactory , you may dispose the HttpClient instance after every use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM