File upload and extension check in ASP.NET razor webmatrix

Hi,
I am trying to upload an image using asp.net razor / webmatrix. The upload works but I want to check the file extension of the image. At the moment I have the following code:

WebImage photo = null;
       var newFileName = "";
       var imagePath = "";
       photo = WebImage.GetImageFromRequest();
       @*if (photo != null)*@
        if ((photo != null) && (photo.ImageFormat == "JPG"))

After uploading, an email is sent. The problem is the last line of code: photo.ImageFormat seems to be blocking all files regardless of type. When I remove that the code works to upload etc.

Any help greatly appreciated.

Regards,
NL

LVL 2
nedloganAsked:
Who is Participating?
 
nedloganConnect With a Mentor Author Commented:
Hi,
I think I solved this myself doing the following:

if (IsPost) {
    var fileSavePath = "";
    var uploadedFile = Request.Files[0];
    fileName = Path.GetFileName(uploadedFile.FileName);
    var fileExtension = Path.GetExtension(uploadedFile.FileName).Trim();
    if (fileExtension != ".jpg" && fileExtension != ".jpeg" && fileExtension != ".gif")
        {
        @: Error: please upload your file in jpg / jpeg or zip format.
      }

I know there may be a more robust way to do this but as a human checks every uploaded file, for now I'll use the simple solution.
Regards,
NL
0
 
strickddCommented:
Don't just check the extension, that's not as accurate as checking the content type. Someone can change the extension of an executable and upload it still if you don't perform the check.

foreach (string file in Request.Files)
{
   HttpPostedFile hpf = Request.Files[file] as HttpPostedFile;
   if (hpf.ContentLength == 0)
      continue;
   if(hpf.ContentType != "text/plain" && hpf.ContentType != "image/gif") //content type list here: http://www.utoronto.ca/web/htmldocs/book/book-3ed/appb/mimetype.html
   {
        //do not upload
    }
}
0
 
nedloganAuthor Commented:
Hi,
But is this going to work within my Razor syntax pages, how does it relate to the code I posted.
The image is in WebImage.GetImageFromRequest not Request.Files[file] as HttpPostedFile??

Regards,
NL
0
 
nedloganAuthor Commented:
No other comments that helped.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.