jquery上传头像图片功能完整前端实例

<!doctype html><html><head><meta charset="utf-8"><title>jquery上传头像</title><script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jquery上传头像</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
</head>
<body>
<img id="pic" style="width:100px;height:100px;border-radius:50%;" src="https://avatar.csdn.net/5/6/2/3_qq_38881495.jpg">
<input id="upload" name="file" accept="image/*" type="file" style="display: none">
<script>
  $(function() {
      $("#pic").click(function() {
          $("#upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传
          $("#upload").on("change", function() {
              var objUrl = getObjectURL(this.files[0]); //获取图片的路径,该路径不是图片在本地的路径
              if (objUrl) {
                  $("#pic").attr("src", objUrl); //将图片路径存入src中,显示出图片
                  upimg();
              }
          });
      });
  });

  //建立一?可存取到?file的url
  function getObjectURL(file) {
      var url = null;
      if (window.createObjectURL != undefined) { // basic
          url = window.createObjectURL(file);
      } else if (window.URL != undefined) { // mozilla(firefox)
          url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) { // webkit or chrome
          url = window.webkitURL.createObjectURL(file);
      }
      return url;
  }
  //上传头像到服务器
  function upimg() {
      console.log(344)
      var pic = $('#upload')[0].files[0];
      var file = new FormData();
      file.append('image', pic);
      $.ajax({
          url: "/uploadImg",
          type: "post",
          data: file,
          cache: false,
          contentType: false,
          processData: false,
          success: function(data) {
              console.log(data);
              var res = data;
              $("#resimg").append("<img src='/" + res + "'>")
          }
      });
  }
</script>
</body>
</html>

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
admin
admin

651 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. Stevengring 0 文章