上传图片时,在页面进行预览

前端页面:

 <div class="container">
        <form class="form-horizontal" enctype="multipart/form-data" method="post" action="">      
            <div class="form-group">
                   <label for="inputUser" class="col-md-2 control-label">照片</label>
                     <div class="col-md-3">
                           <input type="file" name="multipartFile" class="form-control" id="inputUser" >
                           <img src="" id="img" style="width: 100px; height: 150px;">
                     </div>
              </div>
        </form>
 </div>

js代码:
$(function(){
     $("[name='multipartFile']").change(function(){
        // this.files[0]代表的是选择的文件资源的第一个,因为上面写了 multiple="multiple" 就表示上传文件可能不止一个
        // ,但是这里只读取第一个
        var objUrl = getObjectURL(this.files[0]) ;
        if (objUrl) {
            // 在这里修改图片的地址属性
            $("#img").attr("src", objUrl) ;
        }
     }) ;
      // getObjectURL是自定义的函数
     function getObjectURL(file) {
        var url = null ;
        // 下面函数执行的效果是一样的,只是需要针对不同的浏览器执行不同的 js 函数而已
        if (window.createObjectURL!=undefined) { // basic
            url = window.createObjectURL(file) ;
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file) ;
        }
        return url ;
    }
});


猜你喜欢

转载自blog.csdn.net/dearshajing/article/details/78348749