简体   繁体   中英

How to Implement Image Preview for File Input in Asp.net MVC3 using Jquery

I am using Asp.Net MVC and Jquery. I have a form which contains file input control to upload Image .I want to preview the selected image before saving into database.

The code I used is here.

<img id="preview_image" alt="" src="" width="100px" height="120px"/>
<input type="file" name="user_image" id="user_image" onchange="preview(this);"/>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
    function preview(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#preview_image')
                    .attr('src', e.target.result)
                    .width(100)
                    .height(120);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

It is not working in Internet Explorer and Safari. Because 'FileReader' is not supported in these browsers

Is there any other solution without using any Flash plugin? Thanks in advance

您可以按照以下问题查看ActiveX对象FileSystemObjectIE和本地文件读取

Relying on the client to do this will give you headaches and problems long term.

My solution would be to use a confirmation page, where you show the user the image that they uploaded, resized and stored in a temp area. When the user clicks to confirm, save the image to the database. You can then either delete the image or more likely move to a place where it can be used as a cache.

If you don't want to go down the confirmation page route you could submit just the image have it resized and present it back from it temporary area using ajax.

Lastly images in databases are good in theory but they don't scale well particularly if they are very big. Our strategy is to make 6 different versions/size of an uploaded image and save them in the file system, including the original image. This give you the flexibility to use the image at whatever size you need and it keeps you database much lighter.

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