js 实现上传文件

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS文件上传title>
head>
<body>
<div class="img">
    <input type="file" class="add-img" kb_max="100">
    <img src="" alt="">
div>
body>
html>
<script src="static/js/jquery.min.js">script>
<script>
    $(".add-img").change(function () {
        var reads = new FileReader();
        var f = $(this).get(0).files[0];
        if (f == undefined) {
            console.log("请完善图片");
            return;
        }
        var filesize = f.size;
        var maxsize = $(this).attr('kb_max');//K
        var kb_max = maxsize + 'K';
        if (maxsize >= 1024) {
            kb_max = maxsize / 1024 + 'M';
        }
        if ((filesize / 1024) > maxsize) {
            console.log('请上传小于' + kb_max + '的图片!');
            return;
        }
        /** js渲染 */
        reads.readAsDataURL(f);
        var that = this;
        reads.onload = function (e) {
            var _this = this
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var image = new Image();
            image.src = data;
            // 图片先加载完,才可以得到图片宽度和高度
            image.onload = function () {
                console.log(_this.result);
                $(that).parents('.img').find('img').attr("src",_this.result)
            }
        };
        /** 接口上传 */
        // var formData = new FormData();
        // formData.append("file", f);
        // var url = '/uploadfile';
        // console.log(url)
        // $.ajax({
        //     url: url, /*接口域名地址*/
        //     type: 'post',
        //     data: formData,
        //     contentType: false,
        //     processData: false,
        //     success: function (res) {
        //         $(that).parents('.img').find('img').attr("src", res.data.url)
        //     }
        // })
    })
script>

你可能感兴趣的:(jquery,javascript,前端,开发语言)