Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 648
Cata Avatar asked Dec 21 '22 13:12

Cata


2 Answers

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>
like image 73
Ali Habibzadeh Avatar answered Dec 29 '22 11:12

Ali Habibzadeh


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.

like image 44
Karl Laurentius Roos Avatar answered Dec 29 '22 10:12

Karl Laurentius Roos