So I’m using this code for view:
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
This for model:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
Works great unless the user add a file which isn’t an image. How can I assure the file uploaded is an image. Thanks
In case it can helps anyone, Here is a static method for
HttpPostedFileBasethat checks if a given uploaded file is an image:Edit 2/10/2017: According to a suggested edit, added a finally statement to reset the stream, so we can use it later.