牛叔叔 的笔记

好好学习

2019-11-05 12:52

Ajax上传图片

牛叔叔

JavaEE

(996)

(0)

收藏

html表单代码

<div class="avatar-add"><-- 上传头像 -->
     <p>建议尺寸168*168,支持jpg、png、gif,最大不能超过50KB</p>
     <form id="headupload" action="#" method="post" enctype="multipart/form-data">
         <input type="file" name="headimg" style="width: 72px; position: relative;left: 150px;top: 30px;">
     </form>
     <img src="${pageContext.request.contextPath}/fly-3.0/res/images/avatar/${log_userinfo.headurl}">
     <span class="loading"></span>
</div>


JQuery 实现Ajax上传代码

$('#headupload').change(function () {
      // FormData这个对象能打包一个表单的所有数据
       let sendData = new FormData($('#headupload')[0]);
        $.ajax({
             url:'${pageContext.request.contextPath}/user/uploadHead',
             data:sendData,
             type : 'post',
             cache:false,//文件不设置缓存
             processData: false,//数据不被转换为字符串
             contentType: false,//上传文件时使用,避免 JQuery 对其操作
             dataType:"json",
             success:function (res) {
                 if(res == 0){
                       // 重新加载页面
                        location.reload();
                  }
                  if(res==1){
                     alert("不支持该格式");
                  }
             },
            error:function () {
                },
            async:true
      })
})


服务器端代码略。

0条评论

点击登录参与评论