Monday, July 26, 2010

ASP.net MVC file upload

Today's task was simply: upload a file from the local machine and save it out to the 'webserver'.

To do this I created a new controller HomeController.cs and a new View, Home\Index.aspx

The important bit of Home\Index.aspx looked like this:
  <form action="/Home/AddProjectPlan" method="post" enctype="multipart/form-data">
         <label for="file">Filename:</label>
         <input type="file" name="file" id="file" />
       <input type="submit" name="submit" value="Submit" />
     </form>


To HomeController.cs I added the System.IO namespace, and the following method:

[HttpPost, ActionName("AddProjectPlan")] //don't really understand this?
public void Add()
{
foreach (string file in Request.Files) //only posting one element from the form, but this would work for many
{
HttpPostedFileBase postedFile = Request.Files[file] as HttpPostedFileBase;

if (postedFile.ContentLength > 0) //if file not empty
{
string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "temp\\", Path.GetFileName(postedFile.FileName));
postedFile.SaveAs(savedFileName);

// Let user know that it all worked and where the file was saved
Response.Write("File submitted to " + savedFileName);
}
else
{
// Let user know there was a problem
Response.Write("No file submitted or file zero length");
}
}
}

There are a few things in there I don't 100% understand, particularly what the [HttpPost,...] notation at the top means. I tried adding this all into a separate method AddProjectPlan, but for some reason the form post couldn't find this. If anyone has any ideas or decent tutorials, please let me know.

Useful links
While doing this work I found the following very useful:

(and less so)

No comments:

Post a Comment