html上传图片前预览

来源:互联网 发布:iphone6s plus 淘宝 编辑:程序博客网 时间:2024/05/20 10:54

html代码

<tr>
                <td class="td1">身份证正面:</td>
                <td class="td2"><div class="upload" id="img1" style=""></div><input type="file" name="files" id="file1"  onchange="PreviewImage('Preview',this,300,170);" ></input></td>
                <td class="td3 file">*示例图:<img alt="" src="image/sfz1.png"></td>
            </tr>
            <tr>
                <td class="td1">身份证反面:</td>
                <td class="td2" ><div class="upload" id="img2" style="" ></div><input type="file" id="file2" name="files"  onchange="PreviewImage('Preview',this,300,170);"></input></td>
                <td class="td3 file">*示例图:<img alt="" src="image/sfz2.png"></td>
            </tr>
            <tr>
                <td class="td1">银行卡正面:</td>
                <td class="td2"><div class="upload" style="" id="img3"></div><input type="file" id="file3" name="files"   onchange="PreviewImage('Preview',this,300,170);"></input></td>
                <td class="td3 file">*示例图:<img alt="" src="image/sfz2.png"></td>
            </tr>
            <tr>
                <td class="td1 tj" colspan=3 ><input type="button" value="提交" id="tj" onclick="sum()"></td>
            </tr>

ja代码

<script type="text/javascript">
function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

function  checkPic(upload)  {    
    var valid =$(upload).attr('id');
    var  picPath  =  document.getElementById(valid).value;             
    var  type  =  picPath.substring(picPath.lastIndexOf(".")  +  1,  picPath.length).toLowerCase();
    if  (type !== "jpg" && type  !==  "bmp"  &&  type  !==  "gif"  &&  type  !==  "png")  {                 
        alert("请上传正确的图片格式");
        return  false;             
    }             
    return  true;         
}

function PreviewImage(divImage, upload, width, height) {
    if (checkPic(upload)) {
        try {
            var imgPath = getObjectURL(upload.files[0]);
            var divid = $(upload).prev().attr('id');
            
            document.getElementById(divid).innerHTML = "<img id='imgPreview' src='" + imgPath + "' width='" + width + "' height='" + height + "'/>";
            
        } catch (e) {
            alert("无法预览图片");
        }
    }
}

效果

原创粉丝点击