input type="file"文件上传到后台读取

时间:2022-04-01 04:00:03

html页面(表单采用bootStrap)

js部分:

//更换头像时把上传的图片post方式到控制器 <script type="text/javascript">  function upload() {         var files = $('input[name="fileField"]').prop('files');//获取到文件列表   if (files.length == 0) {             alert('请选择文件');  return;  } else {             var reader = new FileReader();//新建一个FileReader  reader.readAsText(files[0], "UTF-8");//读取文件  reader.onload = function (evt) { //读取完文件之后会回来这里  var fileString = evt.target.result;  //post方式上传图片到控制器  var date = {"file": fileString};  $.post("editProfile", date).success(function (result) {                     alert("ok");  });  }         }     } </script>

表单部分

<div class="col-xs-12 col-sm-4 text-center">      <ul class="list-group">         <li class="list-group-item text-left">             <span class="entypo-user"></span>&nbsp;&nbsp;个人资料         </li>         <li class="list-group-item text-center">             <img src="${user.avatar}" alt=""		<!-- ${user.avatar}为头像url地址 -->  class="img-circle img-responsive img-profile">          </li>         <li class="list-group-item text-right" style="text-align: center">             <div id="drag-and-drop-zone" class="uploader">                 <form action="" method="post" enctype="multipart/form-data">                         <span class="btn btn-success btn-file"> 更换头像  <span class="glyphicon glyphicon-picture" aria-hidden="true"></span>           <input type="file" name="fileField" class="file" id="fileField" size="28"  onchange="upload()"/>                 </span>                 </form>             </div>          </li>      </ul>  </div>

控制器部分:

@RequestMapping("editProfile") public ModelAndView editProfile(HttpServletRequest request,@CurrentUser User usaer){     String file=request.getParameter("file");  ModelAndView mv=new ModelAndView();     return mv; }