So in webforms to upload a file here is my default.aspx.cs Submit1 click event
private void Submit1_ServerClick(object sender, System.EventArgs e)
{
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
string SaveLocation = Server.MapPath("Data") + "\\" + fn;
try
{
File1.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
else
{
Response.Write("Please select a file to upload.");
}
}
Below is my Default.aspx HTML for the upload
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<form id="Form1" method="post" enctype="multipart/form-data" runat="server">
<input type=file id=File1 name=File1 runat="server" />
<input type="submit" id="Submit1" value="Upload" runat="server" NAME="Submit1"/>
</form>
</asp:Content>
If you are able to do it via MVC you could do the following
//Disclaimer -- I should have used the Html helper for this but i was being lazy. /Ajax/AddAttachment is the Controller/method name.
<form method="post" enctype="multipart/form-data" class="asform-inline" action="/Ajax/AddAttachment">
<input type="hidden" name="IssueID" id="IssueID" value="@Model.IndexID" />
<input type="file" name="files">
<input type="submit" name="submit" value="Add Attachment" class="btn btn-primary" />
</form>
[HttpPost]
public ActionResult AddAttachment(string IssueID, IEnumerable<HttpPostedFileBase> files)
{
using (UnitOfWork uow = new UnitOfWork())
{
if (files != null)
{
foreach (var file in files)
{
if (file != null)
{
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("~/Content/attachments"), fileName);
file.SaveAs(path);
if (System.IO.File.Exists(path))
{
string filename = string.Format(@"{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(fileName));
System.IO.File.Move(path, Path.Combine(Server.MapPath("~/Content/attachments"), filename));
path = Path.Combine(Server.MapPath("~/Content/attachments"), filename);
}
}
}
}
}
return RedirectToAction("View", "Controller", new { @id = IssueID });
}
}
I did test the web forms one before posting so i do know it uploads files. Im pretty sure its not efficient at all (if it is thats sad) so it could be improved upon. The MVC file upload is merely meant to show a comparison on how file uploads are handled in mvc 3 and greater.
If you have any questions on what i've posted i'll be happy to try and help you out.