Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 934
Cosmos24Magic Avatar asked Sep 11 '25 14:09

Cosmos24Magic


1 Answers

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.

like image 127
galdin Avatar answered Sep 13 '25 05:09

galdin