Search code examples
asp.net-mvc-3file-uploadimageresizer

mvc3 Path.GetExtension issue when uploading file


I am getting an The requested operation cannot be performed on a file with a user-mapped section open error issue when uploading a file been stumped on this for a few days and have isolated the issue.. this code doesn't work

var fileName = Path.GetExtension(file.FileName);


                                var changename = profile.registrationID+ fileName;
                                var mytrail = Path.Combine(Server.MapPath("~/uploads/profilepic"), changename);
                                file.SaveAs(mytrail);
                                ImageBuilder.Current.Build(mytrail, mytrail, new ResizeSettings("width=100&height=130&mode=stretch"));
                                ModelState.Clear();
                                db.Entry(profile).State = EntityState.Modified;
                                db.SaveChanges();
                                return View(profile);

when i tried to upload a picture i get the user-mapped section open error and the ImageBuilder.Current.Build(mytrail, mytrail, new ResizeSettings("width=100&height=130&mode=stretch")); is highlighted . The thing is that in the above code if I change fileName to

var fileName = "abc";

the whole code works picture gets uploaded with no error only thing is that the picture gets saved as a File instead of a .jpg or .gif. What about these 2 lines can possibly be causing the error...

 var fileName = Path.GetExtension(file.FileName);
                                ImageBuilder.Current.Build(mytrail, mytrail, new ResizeSettings("width=100&height=130&mode=stretch"));

This is the imageResizer from http://imageresizing.net/docs/managed


Solution

  • Actually, it's easier than that.

    ImageBuilder.Current.Build(file, 
       "~/uploads/profilepic/" + profile.registrationID + ".<ext>", 
        new ResizeSettings("width=100&height=130&mode=stretch"));
    

    The more you let ImageResizer do, that faster and safer the job wil be done. Your previous code allowed for any extension file to be uploaded - a big potential exploit opportunity. <ext> only allows image extensions.