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
For anyone that runs into this.
You could also use a
file.ContentType.Contains("image")
to check if the content type is of image/*.Not sure if this is best practice, but it works for me.
Usage:
As a first step, you should form a white list around the acceptable MIME types against the
ContentType
property.In case it can helps anyone, Here is a static method for HttpPostedFileBase that 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.
It's 2018 and the accepted answer does not work with .NET CORE 2.1 because we now have
IFormFile
instead ofHttpPostedFileBase
.Here comes the adaption of the accepted answer to .NET CORE 2.1 (I also fixed the bug/typo mentioned by TomSelleck in his comment to the accepted answer):
Don't have the compiler at hand but something like this should do: