Asp Net Download Text File From Url UPDATED

Asp Net Download Text File From Url

Download Files using Web API

How to return a file from an API endpoint in ASP.NET Core and create an HTML download link.

Changhui Xu

In this article, I will use a demo Spider web API application in ASP.Net Cadre to evidence you how to transmit files through an API endpoint. In the final HTML page, end users tin left-click a hyperlink to download the file or correct-click the link to choose "Save Link As" in the context menu and salvage the file.

The full solution can be plant in my GitHub repository, which includes a web project for uploading/downloading files and an integration test project for testing controller methods.

At present let's swoop in.

In ASP.NET Core, a Web API action method usually returns an ActionResult object. When we want to return a file response, we tin explicitly set up the render type for the action method to exist FileResult, which is a type inherited from ActionResult. Only well-nigh times we still desire to employ the generic ActionResult because information technology covers many other useful return types, such every bit BadRequest, NoContent, and then on.

The FileResult type is an abstruse blazon, and it has four physical implementations: FileContentResult, FileStreamResult, VirtualFileResult, and PhysicalFileResult. These four variants don't differ much, you tin utilize any of them to construct a FileResult object at your convenience. In other words, no matter which of the four types you apply, the client-side will not find any departure when downloading a file from the API endpoint.

Apart from the constructors for the four concrete types, we can use a method File, provided natively from the ControllerBase form, to return a physical FileResult object. The File method is very flexible and has a variety of overload methods to instantiate FileContentResult, FileStreamResult, VirtualFileResult, and PhysicalFileResult instances.

With the groundwork laid, we can hands write an activity method as follows:

In the code above, nosotros first discover or generate the requested file from the local file system or a file storage, then read the file content. In the end (line seven), we render a FileContentResult object that is created using the method File(byte[] fileContents, cord contentType, cord fileDownloadName). Note that we should validate the request and user permissions before finding or generating the requested file. And you can choose to stream the file as well.

In the File method (line 7), the 2nd parameter contentType is used in the HTTP header to betoken the format of contents transmitted over the internet. In this demo, the action method returns a text file, so the content type is "text/plain". You can set the value for contentType co-ordinate to your file blazon. In the File method, the third parameter fileDownloadName determines the value for the filename attribute in the content-disposition HTTP response header. Browsers care for this value as the meridian priority to dictate the filename when downloading the file.

To sum upwards, the File method in line 7 sets the HTTP response headers as follows.

An example function of HTTP response headers for downloading a file

If the projection includes Swagger support, then we can try out the API endpoint in the Swagger UI folio. In the responses section, the Swagger UI provides a link for downloading the returned file.

An case Swagger UI page that demos a file downloading API endpoint

Sometimes, the file type should be determined at runtime. For instance, some attachments are PDF files, some files are in CSV format, some are images, then on. Then in this example, we should set the contentType based on the file extension. ASP.Net Core natively supports this kind of translation. An example implementation is equally follows.

In lines 8 to 12, we utilize a FileExtensionContentTypeProvider to get contentType based on the file path. The FileExtensionContentTypeProvider is provided in the NuGet package Microsoft.AspNetCore.StaticFiles (refer to the using argument in line ane). This NuGet bundle is automatically included in ASP.Internet Core Web projects, and information technology provides mappings between many commonly seen file extensions and content types. If the file extension is not in the mappings table, then you can add desired mappings in the post-obit manner.

If this utility is being used in many places, then you can excerpt it into a service class that focuses on content-type mapping.

Web users have become used to clicking a hyperlink to download a file. In that location are many ways to implement the hyperlink. For example, we can create a blob information URL, apply a third-party JavaScript library, or serve files straight from a web server.

In this commodity, we are going to use the simplest way to create an anchor chemical element without any JavaScript. The code is simply one line, as shown in the following snippet.

The href attribute has a value that points to the API endpoint. Hither the href value is api/students/files/one, which can be dynamically set in the front end-end lawmaking according to the path and parameters of our API endpoint. Notice that the URL doesn't have to include the filename or file extension.

Another attribute in the anchor element is the download attribute, which prompts the user to save the linked URL instead of navigating to information technology. You tin read more virtually the download attribute here.

The rendered hyperlink works in all major browsers like Chrome, Edge, and Firefox. Users tin either left-click a download link to download the file or right-click the link to choose "Save Link As" in the context menu and save the file. It works like the screen recording beneath.

screen recording for downloading a file from a hyperlink

Everything works as expected. Awesome!

That'south all for today. We take gone over the details nearly downloading files via Spider web API. I promise you have learned something new.

Thanks for reading.

DOWNLOAD HERE

Posted by: alleneiried.blogspot.com

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel