Created
February 11, 2015 21:16
-
-
Save johnmmoss/02d3586d9cc8d36edcb3 to your computer and use it in GitHub Desktop.
ASP.NET Uploading and Downloading files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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