Johhan Santana
Johhan Santana

Reputation: 2415

How to upload image with custom name with it's original extension?

I'm trying to upload images in a form which I basically have done already, but I want the image to be named specifically for each user who registers.

For example, each email will be unique, if there is another email already in the database then the form will return false (it will not let him/her register).

So what I did was change the file name to the email he/she typed in the form.

But now the file will not have it's original extension (.jpg .png etc).

Is there a way I could pull the file original extension?

Here's what I have in my controller:

[HttpPost]
public AcitonResult Register(Registration signingUp, HttpPostedFileBase avatar)
{
    var db = new AvatarDBEntities();
    if (ModelState.IsValid)
    {
        var FindEmail = db.tblProfiles.FirstOrDefault(e => e.PROF_Email == signingUp.Email);

        if (FindEmail == null)
        {
            var Data = db.tblProfiles.Create();
            Data.PROF_Email = signingUp.Email;

            if (avatar != null)
            {
                string profpic = System.IO.Path.GetFileName(avatar.FileName);
                string profpic_name = signingUp.Email + ".jpg"; //this is what I'm trying to change
                string path = System.IO.Path.Combine(Server.MapPath("~/assets/images/user_images/avatars"), profpic_name);

                avatar.SaveAs(path);
            }

            db.tblProfiles.Add(Data);
            db.SaveChanges();
        }
        else
        {
            ModelState.AddModelError("Email", "That Email already exist.");
            return View();
        }
    }
    return View();
}

View:

@using (Html.BeginForm("Register", "Main", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(r => r.Email, new { @class = "custom-input Email" })<br/>
    @Html.ValidationMessageFor(a => a.Email)<br/>
    <label for="avatar">Profile picture:<span class="required">*</span></label><br />
    <input type="file" name="avatar" id="avatar" /><br/>
    <input type="submit" />
}

The image is in the folder with the name as their email and the extension of .jpg.

I just want to pull the extension of the original file and add it after it pulls the email value.

Thanks.

Upvotes: 0

Views: 814

Answers (2)

C.J.
C.J.

Reputation: 3527

There is a method called Path.GetExtension

Store the extension in a temp variable first, then use it later.

string tempExtension = Path.GetExtension(avatar.FileName);

Upvotes: 0

dav_i
dav_i

Reputation: 28097

What I think you're looking for is

Path.GetExtension(string fileName)

So your code becomes

string profpic_name = signingUp.Email + Path.GetExtension(avatar.FileName);

Upvotes: 3

Related Questions