Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to preview an image that the user is trying to upload. This is the code i am using.This is working fine in all major browsers, but i am wondering if there is a better way to achieve this without using session(even though i am clearing the session ) ? I don't want to use Flash.

   @using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { id = "fileuploadform", @enctype = "multipart/form-data" }))
    {
        <input id="fileupload" type="file" onchange="ChangeImage()" name="files" multiple>
        <div id="preview">
            <img src="#" id="imgThumbnail" alt="preview" />
        </div>

    }
            <script>
            $(function ChangeImage() {
                $('#fileuploadform').fileupload({
                    done: function (e, data) {
                        var d = new Date();
                        $('#imgThumbnail')[0].src = "/Home/ImageLoad?a=" + d.getTime();
                    }
                });
            });
        </script>

[HttpPost]
public ActionResult UploadImage(IEnumerable<HttpPostedFileBase> files, PostViewModel model)
{

    Session["ContentLength"] = Request.Files[0].ContentLength;
    Session["ContentType"] = Request.Files[0].ContentType;
    byte[] b = new byte[Request.Files[0].ContentLength];
    Request.Files[0].InputStream.Read(b, 0, Request.Files[0].ContentLength);
    Session["ContentStream"] = b;
    return Content(Request.Files[0].ContentType + ";" + Request.Files[0].ContentLength);
}

   public ActionResult ImageLoad(int? id)
    {
        byte[] b = (byte[])Session["ContentStream"];
        int length = (int)Session["ContentLength"];
        string type = (string)Session["ContentType"];
        Session["ContentLength"] = null;
        Session["ContentType"] = null;
        Session["ContentStream"] = null;
        return File(b, type);
    }
share|improve this question
add comment

1 Answer

Have you tried this solution?

Preview an image before it is uploaded

This solution is purely client side, and does not needed to be uploaded to your server before preview. :)

share|improve this answer
 
I saw this before, but it doesnt work in IE 8. –  user636525 Jan 21 at 6:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.