JS实现头像本地预览与服务器提交方案

作者:小括号

时间:2026-10-24

浏览:365

本文详细讲解如何在Web端实现头像上传与本地预览功能。通过对比服务器临时存储与本地内存预览两种方案,推荐采用在客户端利用FileReader将图片转换为Base64编码进行即时预览,确认后再通过Ajax异步提交至服务器的做法。文章提供了HTML结构、JS逻辑及CSS样式的完整代码示例,并解释了同步与异步Ajax请求的区别。

文章目录

在用户注册或修改个人资料时,通常需要允许用户在本地选择一张图片作为头像,并即时显示预览效果。

实现该功能主要有两种思路:第一种是将图片先上传至服务器的临时目录,获取URL后再渲染到页面;第二种是在本地内存中直接预览图片,待用户确认提交后,再将数据发送至服务器保存。

这两种方案各有优劣。方案一虽然前端处理简单,但会消耗额外的网络流量和服务器存储资源;方案二则减轻了服务器压力,但会增加浏览器的内存负担,且对浏览器兼容性的要求相对较高。

本文重点介绍第二种方案,即在本地内存中完成图片预览,用户确认无误后再将数据上传至服务器保存。

HTML结构部分,主要包含一个文件输入框用于选择图片,一个用于显示预览区域的容器,以及一个提交按钮。


<div class="reHead">
   <P class="content-format">头像支持jpg、png、jpeg格式,文件大小最大不能超过1M</P>
   <div class="content">
     <form method="post" enctype="multipart/form-data" id="file_upload" class="headForm">
       <div id="test-image-preview" class="iconfont icon-bianjitouxiang">
         <input type="file" name="test" id="test-image-file" class="fileHead" accept="image/gif, image/jpeg, image/png, image/jpg" multiple="multiple">
       </div>
       <div class="headMain">
         <span class="file">上传文件</span>
         <p id="test-file-info" class="fileName"></p>
       </div>
     </form>
   </div>
   <div class="but">
     <button class=" orangeHead" id="upImgSub"><a href="" title=" rel="external nofollow" 编辑资料" target="_blank">保存</a></button>
   </div>
 </div>

JavaScript部分负责监听文件选择事件,利用FileReader API将图片文件读取为Data URL(Base64格式),并设置到预览容器的背景图中,实现本地即时预览。


<script type="text/javascript" src="./jquery.min.js"></script>
  <script>
    var fileInput = document.getElementById('test-image-file'),
      info = document.getElementById('test-file-info'),
      preview = document.getElementById('test-image-preview');
      dataBase64 = '',
    // preview.style.backgroundImage = 'url(../../img/portrait.png)';  //默认显示的图片

    // 监听change事件:
    fileInput.addEventListener('change', upImg);

    // 头像上传逻辑函数
    function upImg(){
      preview.style.backgroundImage = '';    // 清除背景图片
      if (!fileInput.value) {   // 检查文件是否选择:
        $('#test-image-preview').addClass('icon-bianjitouxiang');
        info.innerHTML = '没有选择文件';
      }else{
        $('#test-image-preview').removeClass('icon-bianjitouxiang');
        info.innerHTML = '';
      }
      
      var file = fileInput.files[0];  // 获取File引用
      var size = file.size;
      if (size >= 1 * 1024 * 1024) {   //判断文件大小
        info.innerHTML = '文件大于1兆不行!';
        preview.style.backgroundImage = '';
        $('#test-image-preview').addClass('icon-bianjitouxiang');
        return false;
      }
      
      if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {  // 获取File信息:
        info.innerHTML = '不是有效的图片文件!';
        preview.style.backgroundImage = '';
        $('#test-image-preview').addClass('icon-bianjitouxiang');
        return;
      }

      // 读取文件:
      var reader = new FileReader();
      reader.onload = function (e) {
        dataBase64 = e.target.result;   // 'data:image/jpeg;base64,/9j/4AAQSk...(base64编码)...}'    
        preview.style.backgroundImage = 'url(' + dataBase64 + ') ';
        preview.style.backgroundRepeat = 'no-repeat';
        preview.style.backgroundSize = ' 100% 100%';
      };
      // 以DataURL的形式读取文件:
      reader.readAsDataURL(file);
      // console.log(file);
    }

当用户点击提交按钮时,通过Ajax请求将包含Base64编码数据的JSON对象发送至服务器接口。代码示例中展示了jQuery的ajax方法,其中async属性设置为false表示同步请求,这会锁定浏览器直到请求返回,虽然可行但不推荐;若设置为true则为异步请求,不会阻塞后续代码执行。


$("#upImgSub").click(function () {
      $.ajax({
        type:'post',
        data:{'newHead':dataBase64},
        async:false,   // 当async属性的值为false时是同步的,Ajax请求将整个浏览器锁死,只有ajax请求返回结果后,才执行ajax后面的alert语句。  (虽然可行,但是不推荐)              // 当async属性的值为true时是异步的,即不会等待ajax请求返回的结果,会直接执行ajax后面的alert语句。    (后期介绍异步请求解决回地狱)
        dataType:'json',
        url:'/index/img',
        success:function (res) {  // 返回成功
          if(res.code === 200){
            alert(msg)     // 上传成功
          }else{
            alert(msg)     // 上传失败
          }
        },
        error:function () {
          alert("接口错误");    // 返回失败
        }
      })
    });

当async属性的值为false时是同步的,Ajax请求将整个浏览器锁死,只有ajax请求返回结果后,才执行ajax后面的alert语句。 (虽然可行,但是不推荐) 当async属性的值为true时是异步的,即不会等待ajax请求返回的结果,会直接执行ajax后面的alert语句。 (后期介绍异步请求解决回地狱)

CSS部分定义了头像预览区域的样式,包括圆形边框、背景色、字体大小以及提交按钮的样式,确保界面美观且交互清晰。


body{
  font-size: 12px;
}
.reHead{
  margin: 15px 4%; 
}
.headForm{
  text-align: center;
  padding: 40px 0 70px 0;
}
#test-image-preview {
  position: relative;
  display: inline-block;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  background: #F5F5F5;
  color: #fff;
  font-size: 60px;
  text-align: center;
  line-height: 100px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
  margin-bottom: 26px;
}
.fileHead{
  position: absolute;
  width: 100px;
  height: 100px;
  right: 0;
  top: 0;
  opacity: 0;
}
.content-format {
  font-size: 12px;
  font-weight: 400;
  color: rgba(153, 153, 153, 1);
}
.headMain{
  height: 40px;
}
.file {
  position: relative;
  background: #fff;
  color: #F39800;
  font-weight:800;
}
.file input {
  position: absolute;
  font-size: 12px;
  right: 0;
  top: 0;
  opacity: 0;
}
.fileName {
  line-height: 28px;
  font-size: 12px;
  font-weight: 400;
  color: rgba(51, 51, 51, 1);
}
.but{
  text-align: center;
}
.orangeHead{
  width: 40%;
  height: 40px;
  background: #f60;
  border: none;
}
.orangeHead a{
  color: #fff;
}

以上就是js实现头像上传并且可预览提交的详细内容,更多关于js 头像上传的资料请关注本站其它相关文章!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章