Cosmos24Magic
Cosmos24Magic

Reputation: 229

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?

Upvotes: 4

Views: 12188

Answers (2)

galdin
galdin

Reputation: 14034

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.

Upvotes: 9

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

Upvotes: 5

Related Questions