Page 1 of 1

[ASP.Net MVC2] How to let users download a file.

#1 Sergio Tapia   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1258
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Posted 03 August 2010 - 06:46 PM

Letting your users download a file is extremely easy with MVC2 and it'll save you a lot of time when you need to change or otherwise modify what you already have.

In this tutorial I'll show you how to return a .txt file called download.txt.

Create a new MVC2 application using Visual Studio (I'm using 2010 Ultimate) and navigate to your Controllers folder.

Posted Image

Double-click the HomeController.cs file to see what Actions you have generated. We'll be adding a FileResult action:

public FileResult DownloadFile()
    return File(@"C:\Users\Sergio\Desktop\download.txt", "application/txt", "download.txt");

In my case the file is located on my desktop, but you can give it a path to anywhere on your machine.
The File() method has a lot of overloads, but in this case we're using "Location to File", "MIME type" and "Suggested Filename".

Now compile your code, and try running it. Enter the url http://localhost:123/Home/DownloadFile and your browser will ask you what to do with the file. :)

There's one slight problem. If your enduser has file extensions explicitly shown on his OS, you are going to have to provide a file extension for your suggested name.

My suggestion is to type in the extension manually even if it means your file might be called "download.txt.txt". :P

Thanks for reading!

Is This A Good Question/Topic? 0
  • +

Replies To: [ASP.Net MVC2] How to let users download a file.

#2 Guest_Al*


Posted 12 August 2010 - 07:57 AM

thanks for posting this.. just what i was looking for
Was This Post Helpful? 0

Page 1 of 1