Return to Snippet

Revision: 64768
at September 18, 2013 12:30 by sinanazifi


Initial Code
@model Progresspics_b14.Models.Level

@{
    ViewBag.Title = "Create";
}

<script>
    function previewfile(file) {
        if (tests.filereader === true && acceptedTypes[file.type] === true) {
            var reader = new FileReader();
            reader.onload = function (event) {
                var image = new Image();
                image.id = "imgcrop";
                image.src = event.target.result;

                // 'holder' always is holding only one image. If drag/drop multiple files, then only one last file will be holding there.
                //  if there is already an image holded in 'holder', by drag/drop new image, old image will be replaced with new one.
                while (imageholder.childNodes.length > 0) {
                    imageholder.removeChild(imageholder.lastChild);
                }
                imageholder.appendChild(image);

                api = $.Jcrop('#imgcrop', { onSelect: storeCoords, aspectRatio: 1 / 2, boxWidth: document.getElementById('imageholder').clientWidth });
            };

            reader.readAsDataURL(file);
        } else {
            holder.innerHTML += '<p>Uploaded ' + file.name + ' ' + (file.size ? (file.size / 1024 | 0) + 'K' : '');
            console.log(file);
        }
    }

    function storeCoords(c) {
        jQuery('#X').val(c.x);
        jQuery('#Y').val(c.y);
        jQuery('#Z').val(c.w);
        jQuery('#A').val(c.h);
    }

    function readfiles(files) {

        var formData = tests.formdata ? new FormData() : null;
        for (var i = 0; i < files.length; i++) {
            if (tests.formdata) formData.append('file', files[i]);
            previewfile(files[i]);
        }

        //// now post a new XHR request
        //if (tests.formdata) {
        //  var xhr = new XMLHttpRequest();
        //  xhr.open('POST', '/devnull.php');
        //  xhr.onload = function() {
        //    progress.value = progress.innerHTML = 100;
        //  };

        //  if (tests.progress) {
        //    xhr.upload.onprogress = function (event) {
        //      if (event.lengthComputable) {
        //        var complete = (event.loaded / event.total * 100 | 0);
        //        progress.value = progress.innerHTML = complete;
        //      }
        //    }
        //  }
        //  xhr.send(formData);
        //}
    }
</script>
<style>
    #holder {
        border: 2px dashed #898989;
        min-height: 50px;
        text-align: center;
    }

    #imageholder {
        border: 2px solid #ccc;
        clear: both; /*min-width: 50px;*/
        min-height: 50px; /* margin: 10px auto;*/
    }

    #holder.hover {
        border: 5px dashed #0c0;
    }

    #Text { /*width: 220px;*/
        margin: 10px auto 0 auto;
        position: relative;
        text-align: left;
        color: #bbb;
        font-size: 15px;
    }

    #holder img {
        display: block;
        margin: 10px auto;
    }

    #holder p {
        margin: 10px;
        font-size: 14px;
    }

    progress {
        width: 100%;
    }

        progress:after {
            content: '%';
        }

    .fail {
        background: #c00;
        padding: 2px;
        color: #fff;
    }

    .hidden {
        display: none !important;
    }
</style>

<h2>Create</h2>
<br />
<div>
    @using (Html.BeginForm("create", "Level", FormMethod.Post, new { id = "upload_form", enctype = "multipart/form-data" }))
    {
        
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        <fieldset>
            <legend>Level</legend>
            @Html.HiddenFor(model => model.PostId)

            <div class="editor-label">
                @Html.LabelFor(model => model.LevelDate)
            </div>
            <div>
                <input type="date" id="LevelDate" name="LevelDate" title="Date" />
                @Html.ValidationMessageFor(model => model.LevelDate)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.Description)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Description)
                @Html.ValidationMessageFor(model => model.Description)
            </div>

            <div id="holder">
                <div id="Text">DROP HERE ('jpeg', 'gif', 'png')</div>
            </div>
            <p id="alt_upload">
                <label>
                    Drag & drop not supported, but you can still upload via this input field:<br>
                    <input type="file" id="uplaod_filedialog">
                </label>
            </p>
            <p id="filereader">File API & FileReader API not supported</p>
            <p id="formdata">XHR2's FormData is not supported</p>
            <p id="progress">XHR2's upload progress isn't supported</p>

            <div id="imageholder"></div>

            <input type="hidden" id="X" />
            <input type="hidden" id="Y" />
            <input type="hidden" id="Z" />
            <input type="hidden" id="A" />

            <script>
                var imageholder = document.getElementById('imageholder'),
                    holder = document.getElementById('holder'),
                    tests = {
                        filereader: typeof FileReader != 'undefined',
                        dnd: 'draggable' in document.createElement('span'),
                        formdata: !!window.FormData,
                    },
                    support = {
                        filereader: document.getElementById('filereader'),
                        formdata: document.getElementById('formdata'),
                        progress: document.getElementById('progress')
                    },
                    acceptedTypes = {
                        'image/png': true,
                        'image/jpeg': true,
                        'image/gif': true
                    },
                    fileupload = document.getElementById('alt_upload');

                "filereader formdata progress".split(' ').forEach(function (api) {
                    if (tests[api] === false) {
                        support[api].className = 'fail';
                    } else {
                        // I could have done el.hidden = true, but IE doesn't support
                        // hidden, so I tried to create a polyfill that would extend the
                        // Element.prototype, but then IE10 doesn't even give me access
                        // to the Element object. Brilliant.
                        support[api].className = 'hidden';
                    }
                });

                if (tests.dnd) {
                    fileupload.className = 'hidden';
                    holder.className = '';
                    holder.ondragover = function () { this.className = 'hover'; return false; };
                    holder.ondragend = function () { this.className = ''; return false; };
                    holder.ondrop = function (e) {
                        this.className = '';
                        e.preventDefault();
                        readfiles(e.dataTransfer.files);
                        $('#upload_form').in {
                            formData: { example: 'test' }
                            
                        });
                    };
                } else {
                    holder.className = 'hidden';
                    fileupload.className = '';
                    fileupload.querySelector('input').onchange = function () {
                        readfiles(this.files);
                    };
                }
            </script>

            <p>
                <input type="submit" value="Save" />@Html.ActionLink("Back to List", "Index")
            </p>

        </fieldset>
    }
</div>


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Initial URL

                                

Initial Description
This code can collect and Date and Description from user, then User can drag/drop an image in drop area to load it into browser OR if browser doesn't support drag/drop, then user can see a normal file input instead to browse and choose an image. after that user can determine a crop area for corresponding image. until here everything works charming. If I use a file input as a form field, after submit, in controller function ( by using WebImage static methods) I can get all images existing in request easily. Problem is when I use a drag/drop method to load a image in browser. then there is no File object in Request to could be retrieved in Controller using WebImage methods. 
How can I add this File object somehow to Request?
I can't use Ajax because sometimes user needs to load image in browser and determine a Crop area for that.

Initial Title
How to add a already loaded image into browser, into a form field of type 'file'.

Initial Tags

                                

Initial Language
HAML