Ajax+formData異步文件上傳

前端jsp:javascript

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>html

<%前端

String path = request.getContextPath();java

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";jquery

%>ajax

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">apache

<html>json

  <head>後端

    <base href="<%=basePath%>">dom

    

    <title>ajax文件上傳</title>

<script type="text/javascript" src="js/jquery-2.1.1.js"></script>

   <script type="text/javascript">

  function add(){

   var formdata=new FormData($("#frm")[0]);

   $.ajax({

   type:'post',

   url:'ajaxupload.do',

   data:formdata,

   dataType:'json',

   contentType:false,

   processData:false,

   success:function(data){

   var result=data.result;

   if(result=='1'){

   alert('提交成功!');

   }else{

   alert('提交失敗!');

   }

   },

   error:function(){

   alert('未知錯誤!');

   }

   });

   }

   </script>

  </head>

  

  <body>

   <form method="post" id="frm">

   <table>

   <tr><td>標題:</td><td><input type="text" name="title" /></td></tr>

   <tr><td>內容:</td><td><input type="text" name="content" /></td></tr>

   <tr><td>附件一:</td><td><input type="file" name="ff" /></td></tr>

   <tr><td>附件二:</td><td><input type="file" name="ff2" /></td></tr>

   <tr><td colspan="2"><input type="button" onclick="add()" value="提交"></td></tr>

   </table> 

   </form>

  </body>

</html>

 

 

後端servlet java代碼:

package servlet;

 

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import java.util.UUID;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.json.JSONObject;

 

public class AjaxUploadServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

this.doPost(request, response);

}

 

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

DiskFileItemFactory factory=new DiskFileItemFactory();

ServletFileUpload upload=new ServletFileUpload(factory);

JSONObject js=new JSONObject();

String title="";

String content="";

try {

List<FileItem> items=upload.parseRequest(request);

for(FileItem item:items){

if(item.isFormField()){

//只能經過此形式獲取普通表單域的值,上傳文件,表單form的enctype="multipart/form-data",是以二進制數據流提交數據的。因此無法用request.getParameter("name")來獲取提交到後臺的普通表單域值。

if("title".equals(item.getFieldName())){

title=item.getString("UTF-8");

}else if("content".equals(item.getFieldName())){

content=item.getString("UTF-8");

}

}else{

String fileName=item.getName();

System.out.println("上傳的文件爲:"+fileName);

String path=request.getRealPath("/upload");

File f=new File(path+"/"+UUID.randomUUID()+"-"+fileName);

item.write(f);

js.put("result", "1");

}

}

System.out.println("title:"+title+",content:"+content);

} catch (Exception e) {

e.printStackTrace();

}

out.write(js.toString());

}

 

}

相關文章
相關標籤/搜索