from表单同时提交普通参数和文件

2019-10-10  本文已影响0人  咩咩籽

普通的form表单提交后页面都会跳转,可使用jQuery的ajaxSubmit来防止跳转

需要引入jquery和jquery-from
<script type="text/javascript" src="/js/jquery/jquery.form.js"></script> 
<script type="text/javascript" src="/js/jquery/jquery-1.8.0.min.js"></script>

//使用方法--提交到from表单的action
function submitForm() {
   // jquery 表单提交
   $("#upload").ajaxSubmit(function(message) {
       // 对于表单提交成功后处理,message为表单正常提交后返回的内容
       console.log(message);
   });
   return false; // 必须返回false,否则表单会自己再做一次提交操作,并且页面跳转
}
//使用方法--提交到指定的服务
function submitForm() {
   var form = document.getElementById('upload'),
       formData = new FormData(form);
   $.ajax({
       url:"http://xxxxx/fileupload",
       type:"post",
       data:formData,
       processData:false,
       contentType:false,
       done: function (res) {
           alert('完成了:' + res);
       },
       success:function(res){
           if(res){
               alert("上传成功!");
           }
           console.log(res);
       },
       error:function(err){
           alert("服务故障");
       }
   });

   return false;
}
//body
<form  id="fileUploadForm" action="/lzswh_gld/lyServlet"  method="post" enctype="multipart/form-data">
       <input name="lyid" id="lyid" hidden/>
       <div class="form-group">
           请选择文件:<input id="fileFolder" name="fileFolder" type="file"  /><br>
           <span id="msg" style="color: #F00"></span>
       </div>
       <button type="button" class="btn btn-primary" id="subButton" >上传</button>
   </form>

//servlet获取参数和文件
response.setCharacterEncoding("utf-8");
       response.setContentType("text/html;charset=utf-8");
       PrintWriter writer = response.getWriter();
    // 初始化
       SmartUpload smartUpload = new SmartUpload();
       ServletConfig config = this.getServletConfig();
       smartUpload.initialize(config, request, response);
       try {
           // 上传文件
           smartUpload.upload();
           // 得到上传的文件对象
           File smartFile = smartUpload.getFiles().getFile(0);
           String name = smartFile.getFileName();
           String type=name.substring(name.lastIndexOf("."));
           String newName=System.currentTimeMillis()+"1006"+type;
           // 保存文件
           smartFile.saveAs(FILEPATH+newName, SmartUpload.SAVE_AUTO);
           // 传过来的注册数据
           // 只需要new SmartUpload().getRequest().getParameter(""))就能获取到相应的表单数据
           String lyid = smartUpload.getRequest().getParameter("lyid");
           System.out.println("lyid:  "+lyid);
           saveFile(newName,lyid,type);
           writer.print(true);
       } catch (SmartUploadException e) {
           e.printStackTrace();
           writer.print(false);
       } catch (Exception e) {
           e.printStackTrace();
           writer.print(false);
       }finally {
           writer.flush();
           writer.close();
       }
上一篇下一篇

猜你喜欢

热点阅读