Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I implement file download using MVC4's ApiController?

Using regular Controller I could do it by returning FileResult. The same doesn't seem to work with ApiController. Can it be done? Is it even a right thing to do?

like image 472
Joe Shmo Avatar asked Aug 18 '12 00:08

Joe Shmo


People also ask

How do I download a file from Web API?

In this article, I will use a demo Web API application in ASP.NET Core to show you how to transmit files through an API endpoint. In the final HTML page, end users can left-click a hyperlink to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.

What is the use of Apicontroller?

Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP requests and send response back to the caller. Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder.

What is the name of API function to download data?

download() The download() function of the downloads API downloads a file, given its URL and other optional preferences.

What is the difference between Apicontroller and MVC controller?

The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client. The same because it is MVC platform.


1 Answers

Try this.

[HttpGet]    
public HttpResponseMessage Get()
    {
        var file = HttpContext.Current.Server.MapPath("~/Images/accent.png");
        var stream = new FileStream(file, FileMode.Open);
        var content = new HttpResponseMessage(HttpStatusCode.OK)
                         {
                             Content = new StreamContent(stream)
                         };
        content.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        return content;
    }
like image 119
Md Nazmoon Noor Avatar answered Oct 19 '22 09:10

Md Nazmoon Noor