jQuery - how to make a thumbnail from the input file img

10,078

Solution 1

You can't access the file contents before the file is uploaded to your server, unless you're using Chrome which has some fancy features in this area.

What you can do is upload the file and then fetch the file generated as a thumbnail with PHP, I don't think that's the answer you're looking for thought. So instead, to give you a fair answer: no, you can't do this.

Solution 2

I might have a trick for this:

try:

    <!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                        .attr('src', e.target.result)
                        .width(100)
                        .height(100);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</body>
</html>

Solution 3

I'd recommend using the jQuery FileFive plug-in: https://github.com/JDBurnZ/jquery-filefive

Internet Explorer 10, Firefox and Chrome all support HTML5 File Objects, which allows you to read the file's size, filename and mime type, as well the actual contents of the file; the later of which is useful if you want to display thumbnails of selected images without ever uploading them.

Working jsFiddle Example: http://jsfiddle.net/URqBk/

Example Code:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
        <script type="text/javascript" src="https://raw.github.com/JDBurnZ/jquery-filefive/master/jquery.filefive-0.1.0-rc1.min.js"></script>
        <script type="text/javascript">
            $(function() {
                $(document.body).on('change', 'input[type="file"]', function(event) {
                    var $ = $.filefive(this);
                    $.each($filefive.files(), function(offset, file) {
                        var $img = file.image();
                        $('body').append($img);
                    }
                });
            });
        </script>
    </head>
    <body>
        <form>
            <input type="file" name="myfile" />
        </form>
    </body>
</html>
Share:
10,078
Cata
Author by

Cata

Eager to learn and do new things. I consider myself an open minded person and I appreciate any feedback received because admitting your mistakes it's a good start to make improvements! ;)

Updated on June 19, 2022

Comments

  • Cata
    Cata almost 2 years

    I want to make a fancy image uploading system in html. When the user selects an image into a input file, a thumbnail of the image will show up. As I have read there is no way to get the path of the image from the input file because of the security issues. Can someone tell me how can I make this with javascript (using jQuery)? Thank you!

  • Orbling
    Orbling almost 13 years
    Good for the browsers that support it which is FireFox (3.6+) and Chrome (7+), IE does not yet, even in version 9, nor does Opera. So could not be used generally yet, which is the case with most HTML5 things.
  • makeitmorehuman
    makeitmorehuman almost 13 years
    @Orbling: Well pointed out. for total cross browser compatibility look into replicating this with Flash, Silverlight or Google Gears etc
  • Orbling
    Orbling almost 13 years
    @XGreen: I find that most web development professionals still completely avoid HTML5, the coverage is just not yet at a sufficient level. The number of machines running IE or FF lower than v3.6 as their primary browser is greater than half still I believe.
  • makeitmorehuman
    makeitmorehuman almost 13 years
    @Orbling: Unfortunately you are right. But employers also don't want to have their staff put effort in something that's not going to benefit right away. I am really looking forward to html5 practices becoming more wide spread. I generally recommend that they should be employed and alternatives fallbacks should be implemented for old browsers. This makes the transition faster and easier for those who already are familiar with it.
  • Orbling
    Orbling almost 13 years
    @XGreen: The problem with that is unnecessary cost. The fallback will work in the general case and if so, why produce the newer variant in the first place? Given that the primary purpose of the new variants are to do away with the older, more painful methods. Very difficult to justify in most companies from the fiscal and time budgets.
  • Orbling
    Orbling almost 13 years
    @XGreen: Until browser support on market share is mid-to-upper nineties percentage-wise, I doubt that any major website will be able to do away with the fallback code. Look at the situation with IE6, it has held on so long that Microsoft and Google are leading the charge on actively blocking it and telling users to upgrade.
  • makeitmorehuman
    makeitmorehuman almost 13 years
    @Orbling: I agree with you to a certain level but I cant ignore that html5 improves interactivity, cleaner code, greater consistency, improved semantics, better accessibility, offline application cache, smarter forms and many more things that makes the web a much better place. But yes for now its hard to convince everyone to use it bcoz its extra effort
  • Orbling
    Orbling almost 13 years
    @XGreen: Personally, I favour XHTML and dislike HTML5 semantics, a huge step backwards. But the additional framework features within the DOM application model are highly useful. But sadly, browsers are appalling enough at ensuring cross-browser consistency on the block-model and basic DOM model entries. The likelihood of them getting highly complex features like the Canvas interface to exactly comply is minimal, unless Microsoft decide to do the world a favour and exit the browser market. ;-)
  • makeitmorehuman
    makeitmorehuman almost 13 years
    True. There is nothing like a dream to create the future "Victor Hugo". I believe there are some big changes coming to the web. maybe the move attention to tablets and them focusing on html5 will facilitate or at least catalyse this vendor consistency process
  • Orbling
    Orbling almost 13 years
    @XGreen: With any luck. The modern mobile market is certainly altering the scene. Though I find that most companies still consider the mobile market an "extra", rather than something that will be supported by the main site. The screen size and access methods are still sufficiently different to require a total redesign, so the "different" language remains isolated.
  • Cata
    Cata almost 13 years
    Thank you all for your responses, ok now I understand how the things work... then if I have to upload the file on the server how can I submit the form without refreshing the page? is there a wai of using ajax ?
  • Karl Laurentius Roos
    Karl Laurentius Roos almost 13 years
    Take a look at this: valums.com/ajax-upload you can den use the onSuccess event to fetch the image, preferably as a link to the image as the response from your back-end.