<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>JS文件上传</title>
    <script type="text/javascript" src="../js/jQuery.js"></script>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        
        #img {
            display: block;
            width: 9.98rem;
            height: 6rem;
            border: .01rem solid black;
        }
        
        #file {
            display: block;
            margin: -6rem 0 0 0;
            opacity: 0;
            width: 10rem;
            height: 6rem;
        }
        
        #submit {
            display: block;
            width: 5rem;
            height: 2rem;
            margin: .5rem 2.5rem;
            font-size: .45rem;
            text-align: center;
            line-height: 2rem;
        }
    </style>
</head>
<body>
    <img id="img" src="" />
    <input id="file" type="file" />
    <input id="submit" type="button" value="提交文件" />
</body>
</html>
<script type="text/javascript">
    // rem布局
    $('html').css('font-size', $(window).width() / 10);
    // 实例化文件输入框的读取对象
    var fileReader = new FileReader();
    var base64File = null;
    // 当文件输入框读取到文件时
    $('#file').on('change', function(){
        // 获取文件列表
        var fileList = $("#file")[0].files;
        fileReader.onload = function(e){
            // 获取扩展名
            var extensionName = fileList[0].name.split('.');
            extensionName = extensionName[extensionName.length -1];
            // 获取文件的base64编码
            var base64 = e.target.result;
            // 将读取 文件放置到一个img标签
            $('#img').attr('src', base64);
            // 当文件加载完成后进行压缩
            var img = $('#img')[0];
            img.onload = function(){
                // 将文件和文件扩展名拼接
                base64File = cutDowmImg(img, 100).split(',')[1] + "." + extensionName;
                // 将拼接后的字符串加密
                base64File = encodeURIComponent(base64File);
            }
        }
        fileReader.readAsDataURL(fileList[0]);
    });
    // 提交图片
    $('#submit').on('click', function(){
        console.log(base64File);
        $.post("http://192.168.0.105/WebTest/Base64UploadServlet", {file: base64File}, function(e){
            console.log(e);
        })
    });
    // 压缩图片的方法
    function cutDowmImg(img, width){
        var canvas = document.createElement("canvas");
        canvas.width = Math.min(img.width, width);
        canvas.height = img.height*width/img.width;
        var cxt = canvas.getContext("2d");
        cxt.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
        return canvas.toDataURL();
    }
</script>

 

posted on 2017-04-09 22:04  被遗忘的优雅  阅读(3195)  评论(0编辑  收藏  举报