Create an avatar upload form for users


I'm using ASP.Net MVC 5 and I want to create an avatar for my user profiles. I'm not sure if what I'm doing so far is the right way, especially for security reasons so I wanted to get some advice.

What I'm doing so far

In View:

@using (Html.BeginForm("ManageUser", "Account", FormMethod.Post, new { enctype = "multipart/form-data" }))
    <input type="file" name="file" />
    <input type="submit" value="Add Avatar" />

In controller:

    internal static bool SaveAvatar(User user, HttpPostedFileBase file)
        if (file == null || file.ContentLength <= 0 || file.ContentLength > MAX_LENGTH)
            return false;

        //I think I should convert the file somehow instead of saving it
        var path = HostingEnvironment.MapPath("~/img/avatar/") + string.Format("{0}.png", user.UserName);
        user.HasAvatar = true;

        return true;

I have several concerns:

  • In the code above, as I commented, I think instead of just saving what user has sent to me, I should somehow use a library to convert the image to a PNG file and save it. If so, is there a good and simple library to do this?
  • I wonder whether using the user's name as a file would be good idea. After all, they choose this name and it is not something I decide.
  • Is it a good idea to use plain images or should I create a controller to validate requests or rout the requests to a hidden image?

If what I'm doing is TOTALLY wrong and you know a better source to learn the right way, please point me in the right direction. Thanks.


I found this post very helpful and I wanted to share my implementation of Sirwan Afifi's excellent answer. I needed the resize function to take and return an image so it's a little different. However I've also added a boolean to preserve the aspect ratio of an image if you want.

public static Image ResizeImage(Image img, int width, int height, bool preserveAspectRatio = false)

        int newWidth;
        int newHeight;

        if (preserveAspectRatio)
            int originalWidth = img.Width;
            int originalHeight = img.Height;
            float percentWidth = (float)width / (float)originalWidth;
            float percentHeight = (float)height / (float)originalHeight;
            float percent = percentHeight 
By : DasAmigo

This video can help you solving your question :)
By: admin