A local preview instance of a Javascript image before uploading

  • 2020-03-30 03:20:03
  • OfStack

Image upload preview function is mainly used for a preview of the effect before image upload, the current mainstream methods are mainly js, jquery and flash implementation, but we will generally use js to achieve image upload preview function, let's look at an example.

Principle:

There are two steps: when the input to upload an image is triggered and the local image is selected, the URL of the object to be uploaded is obtained (object URL); The image is displayed by assigning the object URL to the SRC attribute of the prewritten img tag.

Here, we need to know about Javascript File object, the Blob object and window. The URL. CreateObjectURL () method.

The File object:

A File object can be used to get information about a File and also to read the contents of that File. Typically, a File object is a FileList object returned after the user selects a File on an input element, or a DataTransfer object generated by a drag-and-drop operation.
Here's how to get the FileList object:


<script type="text/javascript" src="jquery.js"></script>
<input id="upload" type="file">
<img id="preview" src="">
<script type="text/javascript">
$('#upload').change(function(){
    //Gets the first element of the FileList
    alert(document.getelementbyid('upload').files[0]);
});
</script>

A Blob object:


<script type="text/javascript">
var f = document.getelementbyid('upload').files[0];
var src = window.URL.createObjectURL(f);
document.getElementById('preview').src = src;
</script>

Compatibility:

This works for chrome
If you are an Internet explorer browser, you can directly use the value of input to replace SRC
The getAsDataURL() method of the File object is used to get the URL. This method has been abolished. Similarly, the getAsText() and getAsBinary() methods are used.


function getFullPath(obj) {    //Get the full path of the image & NBSP;
    if (obj) {  
//ie  
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {  
    obj.select();  
    return document.selection.createRange().text;  
}  
//firefox  
else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {  
    if (obj.files) {  
return obj.files.item(0).getAsDataURL();  
    }  
    return obj.value;  
}  
return obj.value;  
    }  
}

This code is the full path to get the client's picture
Let's limit the size and format


$("#loadFile").change(function () {  
var strSrc = $("#loadFile").val();  
img = new Image();  
img.src = getFullPath(strSrc);  
//Verify that the uploaded file format is correct & NBSP;
var pos = strSrc.lastIndexOf(".");  
var lastname = strSrc.substring(pos, strSrc.length)  
if (lastname.toLowerCase() != ".jpg") {  
    alert(" The file type you uploaded is " + lastname + " , the picture must be  JPG  type ");  
    return false;  
}  
//Verify upload file width/height ratio & NBSP;

if (img.height / img.width > 1.5 || img.height / img.width < 1.25) {  
    alert(" The proportion of the picture you upload is out of range, the aspect ratio should be between 1.25-1.5");  
    return;  
}  
//Verify that the uploaded file is out of size & NBSP;
if (img.fileSize / 1024 > 150) {  
    alert(" The size of the file you uploaded has exceeded 150K Limit! ");  
    return false;  
} 

Where loadFile is the id of the HTML input file. After its change event, that is, after the file to be uploaded is selected, will the image be displayed in the picture box? Add the following code at the end of the above code


$("#stuPic").attr("src", getFullPath(this));

Now that jQuery is in use, let's share another example of code written in jQuery:


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js"></script>
<script language="javascript">
 $(function(){
        var ei = $("#large");
        ei.hide();
        $("#img1").mousemove(function(e){
                ei.css({top:e.pageY,left:e.pageX}).html('<img style="border:1px solid gray;" src="' + this.src + '" />').show();
        }).mouseout( function(){
                ei.hide("slow");
        })
        $("#f1").change(function(){
                $("#img1").attr("src","file:///"+$("#f1").val());
        })
 });
</script>
<style type="text/css">
        #large{position:absolute;display:none;z-index:999;}
</style>
</head>
<body>
<form name="form1" id="form1">
<div id="demo">
<input id="f1" name="f1" type="file" />
<img id="img1" width="60" height="60">
</div>
<div id="large"></div>
</form>
</body>
</html>


Related articles: