Ajax实现文件上传需要两个jar包:commons-fileupload-1.3.1.jar,commons-io-2.4.jar 和两个js文件ajaxfileupload.js,jquery.js
实例:
ajaxFileUpload.jsp
<script type="text/javascript" src="source/jquery.js"></script>
<script type="text/javascript" src="source/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload() {
$.ajaxFileUpload({
url:"FileUploadAjax",// servlet请求路径
type:"POST",
secureuri:false,
fileElementId:"file",// 上传控件的id
dataType:"json",
data : {"username": "zhangsan"},// 其它请求参数
success:function(data,status) {
alert(data.name);
},
error:function(data,status,e) {
alert("上传出错");
}
});
return false;
}
</script>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input id="file" type="file" name="file"/>
<button class="button" onclick="return ajaxFileUpload();">上传</button>
</form>
</body>
AjaxFileUpload.java
package controller; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; 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.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUploadAjax extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { System.out.println("----------------"); request.setCharacterEncoding("utf-8"); // 设置编码 response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); DiskFileItemFactory dfif=new DiskFileItemFactory(); ServletFileUpload sfl=new ServletFileUpload(dfif); String path=request.getSession().getServletContext().getRealPath("file"); System.out.println(path); String name=null; try { List<FileItem> list=sfl.parseRequest(request); System.out.println(list.size()); for(FileItem fi:list) { if(!fi.isFormField()) { File file=new File(path,fi.getName()); fi.write(file); System.out.println("ok--------------------"); }else{ name=fi.getString(); System.out.println(name+"00000000000000000"); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ PrintWriter pw=response.getWriter(); String result="{\"name\":\""+name+"\"}"; System.out.println(result); pw.println(result); pw.flush(); } } public void doPost(HttpServletRequest request,IOException { this.doGet(request,response); } }
原文链接:https://www.f2er.com/ajax/164209.html