首先看下upload.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>
    <link rel="stylesheet" href="css/up.css">
</head>
<body>
<div class="divcss">
    <div class="portrait">
        <img src="img/avatar.png" alt="" class="avatar" id="imgupload">
        <p>头像</p>
    </div>
    <div  class="file">
        点击上传 <input  type="file" id="profile_pic" >
    </div>
</div>

</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
    //上传个人头像
    $("#profile_pic").change(function (e) {
        console.log(e);
        var file = e.target.files[0] || e.dataTransfer.files[0];
        if (file) {
            //.............
            console.log(file);
            var file = document.getElementById("profile_pic").files[0];
            var formData = new FormData();
            formData.append('file', file); //为ajax的data做准备
            var reader = new FileReader();
            reader.onload = function () {
                $("#imgupload").attr("src", this.result);
            };
            reader.readAsDataURL(file);
            $.ajax({
                url: url + "api/uploadOss/uploadFile",//这是你的后端接口地址
                type: "post",//ajax请求类型
                data: formData,//存放图片资源
                contentType: false,
                processData: false,
                mimeType: "multipart/form-data",
                success: function (data) {
                    //成功返回信息
                    alert("上传成功");
                },
                error: function (data) {
                   //失败返回信息
                    alert("上传头像失败");
                }
            });

        }


    });
</script>
</html>

其次看下up.css文件

body {background-image:url('../img/point.png');}
.divcss {
    margin: 0 auto;
    width: 400px;
    height: 100px;
    text-align: center
}


.avatar {
    width: 350px;
    height: 400px
}
.file {
    position: relative;
    display: inline-block;
    background: #D0EEFF;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
}
.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
.file:hover {
    background: #AADFFD;
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
}

其中有几处用到了图片背景,这个你可以根据喜好选择图片,当然也可以不用。

我的目录结构是这样子的:

img

最终的效果图是这样的:

img

码完收工。


一个可爱的人