我的位置: 主页 > 技术交流区 >

青鸟老师教你如何ajax结合java上传文件

时间:2018-12-29 17:06来源:未知 作者:北大青鸟科海技术 点击:
利用ajax异步上传文件
js 的 XMLHttpRequest Level 2添加了一个新的接口FormData.利用FormData对象,我们可以通过JavaScript用一些键值对来模拟一系列表单控件,我们还可以使用XMLHttpRequest的send()方法来异步的提交这个"表单".比起普通的ajax,使用FormData的最大优点就是我们可以异步上传一个二进制文件.
表单如下:
 
<%page language="java"   pageEncoding="utf-8"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="css/admin.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function(){
    $("#upload").click(function(event){
         event.preventDefault();
        
        var f=$("#uploadForm")[0];//dom
        //alert(f.action+">>>>>");
        var mydata=new FormData(f);//利用form创建对象。mydata.append以手工添加对象
        //
        /**$.post("upload.do",data,function(d){
            alert(d);
        });**/
        $.ajax({
            url:"upload.do",
            type:"POST",
            data:mydata,
            contentType:false,
            processData:false,
            success:function(d){alert(d);f.reset();}
        });
    });
    //
    $("#nfile").change(function(){
        
        var file=this.files[0];
        var preview=$("#preview").get(0);
        
        var reader = new FileReader();
         reader.onloadend = function () {
          preview.src = reader.result;
         }
         if (file) {
          reader.readAsDataURL(file);
         } else {
          preview.src = "";
         }
    });
});
</script>
</head>
<body>
<div id="header">
  <div id="welcome">使</div>
  <div id="nav">
    <div id="logo"><img src="images/logo.jpg" alt="" /></div>
    <div id="a_b01"><img src="images/a_b01.gif" alt="" /></div>
  </div>
</div>
 
<div id="main">
  <div id="opt_area">    
 <h1 id="opt_type">  </h1>
    <form action="upload.do"  enctype="multipart/form-data" method="post" id="uploadForm">
    
      <p>
        <label>  </label>
        <input name="ntitle" id="ntitle" type="text" class="opt_input" />
      </p>
      <p>
        <label>  </label>
        <input name="nauthor" id="nauthor" name="nauthor" type="text" class="opt_input" />
      </p>
      
      <p>
        <label>  </label>        
         <img src="" id="preview" height="200" width="300" alt=""/><br/>
        <input type="file" name="nfile" id="nfile"/>
       
      </p> 
      <input type="submit" value="" class="opt_sub" id="upload" />
      <input type="reset" value="" class="opt_sub" />
    </form>
  </div>
</div>
</body>
</html>
 
后台的处理按照正常的文件上传处理,如下的代码采用common-upload
 
        request.setCharacterEncoding("utf-8");
        // response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        DiskFileItemFactory d = new DiskFileItemFactory();
        ServletFileUpload up = new ServletFileUpload(d);
        up.setHeaderEncoding("utf-8");// 
        try {
            List<FileItem> fields = up.parseRequest(request);// 
            String picPath = super.getServletContext().getRealPath("images");// 
            String title = nullauthor = null;
            for (FileItem f : fields) {
                if (f.isFormField()) {
                    if (f.getFieldName().equals("ntitle"))
                        title = f.getString("utf-8");
                    else if (f.getFieldName().equals("nauthor"))
                        author = f.getString("utf-8");
                    // ....
                } else {
                    if (f.getName() == "")
                        continue;
                    String newFileName = f.getName();
                    f.write(new java.io.File(picPathnewFileName));
                    // 
                }
            }
        } catch (Exception e1) {
            // 
            e1.printStackTrace();
            response.getWriter().print("");
            // response.sendError(500, "" + e1.getLocalizedMessage());
            return;
        }
        // request.setAttribute("msg", "");
        // response.sendRedirect("newsServlet");
        response.getWriter().print("");
    
 
----------------------------分隔线----------------------------