Skip to content

Instantly share code, notes, and snippets.

@johnmmoss
Created February 11, 2015 21:16
Show Gist options
  • Save johnmmoss/02d3586d9cc8d36edcb3 to your computer and use it in GitHub Desktop.
Save johnmmoss/02d3586d9cc8d36edcb3 to your computer and use it in GitHub Desktop.
ASP.NET Uploading and Downloading files
// Sample model uses HttpPostedFileBase to pass the file to the controller
public class CustomerStatementModel
{
public int Id { get; set; }
public string Description { get; set; }
public HttpPostedFileBase CustomerStatementFile { get; set; }
}
// POST:/Customer/Statement
// To upload a customer statment post to this action
[HttpPost]
public async Task<ActionResult> Statement(CustomerStatementModel model)
{
if (model.CustomerStatementFile.ContentType != "excel" || !model.CustomerStatementFile.FileName.EndsWith("xls"))
{
ModelState.AddModelError("CustomerStatementFile", "Must be excel");
return View();
}
var filePath = Path.Combine(FileServerPath, Path.GetFileName(model.CustomerStatementFile.FileName));
using (FileStream stream = System.IO.File.Create(filePath))
{
model.CustomerStatementFile.InputStream.Seek(0, SeekOrigin.Begin);
await model.CustomerStatementFile.InputStream.CopyToAsync(stream);
stream.Close();
}
return Redirect("Index");
}
// GET /Customer/Statement/2
[HttpGet]
public ActionResult Statement(int id)
{
var customerFile = repository.GetCustomerStatementFile(id);
if (customerFile == null)
{
return HttpNotFound();
}
var filePath = Path.Combine(FileServerPath, customerFile.FileName);
if (!System.IO.File.Exists(filePath))
{
return HttpNotFound();
}
var mimeType = filePath.EndsWith(".xlsx") ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" : "application/vnd.ms-excel";
return File(filePath, mimeType, Path.GetFileName(filePath));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment