MVC JScript Upload a Photo and Display Preview


I have a requirement for a user to be able to upload a photo of an item when creating a new record.

Fine easy enough, what I'm having trouble with is previewing the upload before submittal

Here is what I have so far which runs all apart the last line.

            <img id="AssetPic" src="~/Content/missing.png" alt="Upload Photo" width="250" height="250" /><br />
            <input type="file" accept="image/*" onchange="loadFile(event)" name="fileupload" />
                function createObjectURL(file) {
                    if (window.webkitURL) {
                        return window.webkitURL.createObjectURL(file);
                    } else if (window.URL && window.URL.createObjectURL) {
                        return window.URL.createObjectURL(file);
                    } else {
                        return null;

                var loadFile = function (event) {
                    var output = document.getElementById('AssetPic');
                    output.alt = "Your Photo";
                    output.src = createObjectURL(event.currentTarget.files[0]);

Problem Line

 output.src = createObjectURL(event.currentTarget.files[0]);

Error Message

0x800a138f - JavaScript runtime error: Unable to get property 'files' of undefined or null reference

Yet if I copy and paste this in a lonely notepad file and run it, it works fine which leads me to believe the property [files] is being interfered with by another script.

Its a Standard MVC5 App the only script I've added to it is JSpritely.

Does anyone know a solution to get this to work? its stupidly frustrating!

asked on Stack Overflow Oct 18, 2016 by L Riley

1 Answer


Make sure IE's Compatibility mode isn't turned on..... face palm

answered on Stack Overflow Dec 2, 2016 by L Riley

User contributions licensed under CC BY-SA 3.0