简体   繁体   中英

Display image selected for uploading before upload not working

I am trying to display an image after selecting from the hard drive before it is sent to the server (upload). I found a small code on this website, I copy pasted it but it's not working (it is on the demo page). I can select an image and it's name is displayed to the right of the Choose File button, but neither the image nor the size is displayed. I am pulling my hairs out.

Whole code:

<!DOCTYPE html>  <!-- Using margin:auto will not work in IE8, unless a !DOCTYPE is declared. -->
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">

 <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <link href="design3.css" rel="stylesheet" type="text/css"/>

    <script src="jquery-1.8.3.min.js"></script>

<script language="JavaScript">

// Handle file while select a new file
$('#file').change(function () {
    $('#img_size').val((this.files[0].size) / 1000000);
    handleFiles(this.files);
});


// handle files
function handleFiles(files) {
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var imageType = /image.*/;
        if (!file.type.match(imageType)) {
            continue;
        }
        var img = document.getElementById('fake_img');
       /* img.src = file;
        img.onload = function () {
        }; */
        var reader = new FileReader();
        reader.onload = (function (aImg) {
            return function (e) {
                aImg.src = e.target.result;
            };
        })(img);
        reader.readAsDataURL(file);
    }
}



function drawAd() 
{
    window.open('http://www.google.com');
}

</script>

</head>
<body> 

    <input type="file" id="file"/>
    <input type="text" id="img_size" />
    <img src="" id="fake_img" />

    <button type="button" onclick="drawAd()">Refresh</button>


</body>
</html>

Tested in IE and Chrome.

It's hard to know for sure without seeing the rest of your code (the HTML for the form), but probably what's happening is that your code is running before the browser has seen and parsed your HTML.

Wrap your code as a jQuery "ready" handler:

$(function() {
  // your code here
});

and see if that helps. This line:

$('#file').change(function () {

sets up an event handler for the "change" event on the file input. When that runs, if there's no element that the browser knows about with "file" as its "id", then you'll get no error but nothing will happen. By delaying that code until the browser has seen your whole document (which is what that jQuery "ready" wrapper does), you make it such that the "file" input can be found.

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