Danny
Danny

Reputation: 3665

Saving an image from HTML form in ASP.net MVC 3 C#

I'm hoping someone can modify my code below to show me exactly how to get this to do what I want.

I have an HTML form that posts to the following action:

public ActionResult Create(string EntryTitle, string EntryVideo, HttpPostedFileBase ImageFile, string EntryDesc)
    {
        if (Session["User"] != null)
        {
            User currentUser = (User)Session["User"];

            string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(ImageFile.FileName)); 
            ImageFile.SaveAs(savedFileName);

            Entry newEntry = new Entry();

            newEntry.Title = EntryTitle;
            newEntry.EmbedURL = EntryVideo;
            newEntry.Description = EntryDesc;
            newEntry.ImagePath = savedFileName;
            newEntry.UserId = currentUser.UserId;

            db.Entries.Add(newEntry);
            db.SaveChanges();


        }

        return RedirectToAction("MyPage", "User");
    }

This saves the image to the root solution directory (or tries to, doesn't have permission and throws exception instead).

What I would like it to do is the following:

1.) Verify that the file size is under some maximum, let's say 500kb for now

2.) Assuming file size is okay, save it to the following directory

mywebsite.com/uploads/<userid>/<entryid>/entry-image.<jpg/png/gif>

I'm not sure how to rename the file since I want to accept different file extensions (.jpeg, .jpg, .png, .gif). Or unsure how to get it into the correct directory like above. Or how to validate file size, since apparently you can only do that with javascript if the user is using IE.

Upvotes: 0

Views: 1349

Answers (2)

koolpitt
koolpitt

Reputation: 39

hope this helps or at least points you in the right direction

    if (ImageFile.ContentLength < 1024 * 500)
            {
                Entry newEntry = new Entry();

                newEntry.Title = EntryTitle;
                newEntry.EmbedURL = EntryVideo;
                newEntry.Description = EntryDesc;
                newEntry.UserId = currentUser.UserId;

                db.Entries.Add(newEntry);
                db.SaveChanges();  //this helps generate an entry id

                string uploadsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploads");
                string userDir = Path.Combine(uploadsDir, <userid>);
                string entryDir = Path.Combine(userDir, newEntry.EntryID );

                if (Directory.Exists(userDir) == false)
                    Directory.CreateDirectory(userDir);

                if (Directory.Exists(entryDir) == false)
                    Directory.CreateDirectory(entryDir);

               string savedFileName = Path.Combine(entryDir, <entry-image>);
               ImageFile.SaveAs(savedFileName);

               newEntry.ImagePath = savedFileName;  //if this doesn't work pull back out this entry and adjust the ImagePath
               db.SaveChanges();

            }

You should grant a write permission to the 'uploads' directory.

you can also limit file sizes for your web app from the web.config

    <system.web>
       <httpRuntime   maxRequestLength="500"/>

Upvotes: 0

John W
John W

Reputation: 1512

1.Verify that the file size is under some maximum, let's say 500kb for now

You can use the HttpPostFileBase.ContentLength property to get the size (in bytes) of the file.

if (ImageFile.ContentLength > 1024 * 500) // 1024 bytes * 500 == 500kb
{
    // The file is too big.
}

2.Assuming file size is okay, save it to the following directory

string savedFileName = Server.MapPath(string.Format("~/uploads/{0}/{1}/entry-image{2}",
    currentUser.UserId,
    newEntry.EntryId,
    Path.GetExtension(ImageFile.FileName)));

The only problem I see is that it looks like your Entry.EntryId might be generated at the database so you won't be able to use it as part of the save path until it's been generated.

Upvotes: 1

Related Questions