简体   繁体   中英

Handling file upload from HTML form in ASP.net MVC 3 c#

I have plenty of experience with this in PHP, but am fairly new to ASP.net. I've found some tutorials around the web which have gotten me this far, but I am currently running into issues.

So to summarize what I'm trying to accomplish, I have a page where I want users to submit contest entries. I use a HTML form to collect things like entry title, description, and want to allow them to be able to submit an image representing their entry.

When they choose to provide an image, I want it uploaded using a path something like: //entries//entry-image.

My database will simply hold a varchar representing the image path. I would like to add some obvious validations to the file upload as well, such as limiting the file size, and only allowing certain file extensions. The image should be saved with some standard name (like 'entry-image' in the path above), overwriting any image that may already be in that entry directory.

Right now getting text input from my HTML form is not a problem, but getting the file is. I currently have no validation on the form yet, just trying to get it to work in its most basic state. Here is a truncated version of my HTML:

<form method="post" action="../Entry/Create">
            <input type="text" id="EntryTitle" name="EntryTitle" />
            <p id="char-remaining">(100 characters remaining)</p>

            <input type="text" id="EntryVideo" name="EntryVideo" />
            <p id="vid-desc">(URL of the Video to Embed)</p>

            <input type="file" id="ImageFile" name="ImageFile" />
            <p id="file-desc">(200x200px, jpeg, png, gif)</p>

            <textarea id="EntryDesc" name="EntryDesc"></textarea>
            <p id="entry-desc"></p>
            <button id="new-entry-save">save</button>
</form>

Now, here is my Create action in my EntryController class:

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");
    }

You'll notice I have a few lines commented out. When left commented out, the text input values are received just fine and stored in my database. However, left uncommented, a NullReferenceException is thrown on that first commented-out line.

The code I'm using in my action is pretty much just copied and pasted from a tutorial, and I realize that if it did work that it wouldn't be accomplishing the goals I wrote above since it doesn't check for file extension or change the filename to something standard.

So my major questions are:

1.) Why am I receiving a NullReferenceException when I am in fact providing a file on the HTML form?

2.) How would I go about validating the file submitted? (size, extension, dimensions, etc)

3.) How would I go about changing the name of the file to something like 'entry-image'?

Here's an answer to number 2 above:

Call a JavaScript function on your Submit action for that View

<input type="submit" id="thePageSubmit" value="Upload" onclick="return IsValidExtention();" /> 

Then in the Javascript fuinction do something like

    function IsValidExtention() {
        var it = document.forms[0].elements["ImageFile"].value;
        it = it.substring(it.lastIndexOf('\\') + 1);
        if (it.length > 0) {
            if (it.toLowerCase().indexOf(".exe")!=-1) {
                alert("We are unable to upload .exe files.");
                return false;
            }
            if (it.toLowerCase().indexOf(".js") != -1) {
                alert("We are unable to upload .js files.");
                return false;
            }
        }
        else{
            return false;
        } 
        return true;
    }

If it's not already there, add the enctype="multipart/form-data" attribute to your form element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM