美文网首页Web前端之路
前端js上传照片实现可预览功能

前端js上传照片实现可预览功能

作者: 祈澈菇凉 | 来源:发表于2019-06-11 17:35 被阅读169次

在写项目的时候,遇到了上传照片的功能,根据项目的需要,有很多种写法,有些需要上传之前对图片进行裁剪,有些直接上传到页面预览即可,再次之前,用过插件写了两次。用到的都是不同的插件,今天用jquery直接写了一个简单的功能。

bootstrap+fileinput插件实现可预览上传照片功能
https://www.jianshu.com/p/8df97db49798
这个插件的思路是在上传图片的时候就把图片存到服务器的根目录里面,给前端返回一个url即可。

基于cropper.js的图片上传和裁剪
https://www.jianshu.com/p/f9986bd52ec6

<!DOCTYPE HTML>
<html>

    <head>
        <title>新增地图配置</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
        <style>
            #img {
                width: 100px;
                height: 100px;
            }
        </style>
    </head>
    <body>
        <form id="dialogForm">
            <div class="row">
                <div class="col-md-12 col-sm-12  col-xs-12">
                    <div class="form-group">
                        <label class="col-md-3 col-sm-3  col-xs-3 control-label">图标</label>
                        <div class="col-md-6 col-sm-6  col-xs-6">
                            <img src="" id="img" class="hide">
                            <input type="file" name="file" id="file" multiple="multiple" />
                        </div>
                    </div>
                </div>
            </div>
        </form>
        <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
        <script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
        <script>
            $("#file").change(function() {
                var objUrl = getObjectURL(this.files[0]);

                if(objUrl) {
                    $("#img").attr("src", objUrl);
                    $("#img").removeClass("hide");
                }
            });
            //建立一个可存取到file的url
            function getObjectURL(file) {
                var url = null;
                url = window.webkitURL.createObjectURL(file);
                return url;
            }
        </script>
    </body>
</html>

关于浏览器兼容问题,上面写道的是在谷歌浏览器可用,要在火狐ie浏览器里面同样适用只需要在代码里面加上一段适配的代码,判断使用哪个浏览器打开即可。

//建立一个可存取到file的url
    function getObjectURL(file) 
    {
        var url = null ;
        url = window.webkitURL.createObjectURL(file) ;
        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
            
        }
        return url ;
    }


原文作者:祈澈姑娘 技术博客:https://www.jianshu.com/u/05f416aefbe1
90后前端妹子,爱编程,爱运营,文艺与代码齐飞,魅力与智慧共存的程序媛一枚。坚持总结工作中遇到的技术问题,坚持记录工作中所所思所见,前端资源下载群:440185135

相关文章

网友评论

    本文标题:前端js上传照片实现可预览功能

    本文链接:https://www.haomeiwen.com/subject/kqgqfctx.html