jquery实现异步读取图片上传图片到服务器



2016-01-05 15:25 
爱情香烟 
阅读(787
评论(0
编辑 
收藏 
举报

跨域

我们知道JS和服务端交互有跨域的问题,要解决跨域问题有两种方案

1、使用JSONP协议

2、在服务端解决,比如,如果web服务器使用的是nginx可以在配置文件里添加

add_header "Access-Control-Allow-origin" http://xxx.com;

 前端H5代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="//cdn.bootcss.com/jquery/3.0.0-alpha1/jquery.js"></script>
</head>
<body>

<form>
    <input id="input" type="file">

    <input type="button" onclick="uploadFile();" name="ffff" value="rerer">
</form>

<script>

    function uploadFile()
    {
        var selected_file = document.getElementById(\'input\').files[0];
        var reader = new FileReader();
        reader.onloadend = function(e) {
            var bin = e.target.result;
            var data = {
                "image_binary":bin
            };
            $.ajax({
                type: \'POST\',
                url: "http://xxxx/Image/UploadImage",
                data: data,
            });
        };
        reader.readAsDataURL(selected_file);
    }



</script>
</body>
</html>

以上代码使用了jqery的http post请求,另外就是使用了FileReader

注意:reader.onloadend 代码读取文件完成后触发


 服务端代码

    public static function saveBinaryImage($binaryImage)
    {

        list($type, $data) = explode(\',\', $binaryImage);
        if(strstr($type,\'image/jpeg\')!==\'\'){
            $ext = \'.jpg\';
        }elseif(strstr($type,\'image/gif\')!==\'\'){
            $ext = \'.gif\';
        }elseif(strstr($type,\'image/png\')!==\'\'){
            $ext = \'.png\';
        }
        $filename  = "dxxxxxxx";
        $trueFile = $filename . $ext;
        file_put_contents($trueFile , base64_decode($data), true);
        $imageInfo = getimagesize($trueFile);
        $imageWidth = $imageInfo[0];
        $imageHiegh = $imageInfo[1];
        if(!$imageWidth || !$imageHiegh)
        {
            return false;
        }
    }

 

版权声明:本文为aqsmoke原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/aqsmoke/articles/5102460.html