使用jquery.form.js做文件上传。
首先明确一点:当form的enctype属性设置为multipart/form-data时, 在servlet中用request.getParameter(“name”);获取不到对应的值, 需要使用到其他第三方的jar。 (被坑了一晚上, 一直再搞request.getParameter(“name”)获取不到值的问题!悲哀呀)
需要的第三方资料
jsp代码:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>jQuery form</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/pluging/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/pluging/jquery.form.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/dev/submit_form.js"></script>
<body>
<form id="uploadForm" method="post" enctype="multipart/form-data">
<input type="hidden" id="url" value="${pageContext.request.contextPath }/studyForm"/>
name:<input type="text" name="name" id="name" /><br />
password:<input type="hidden" name="password" id="password" value="passwod-value" /><br />
图片:<input type="file" name="pic" id="pic" />
<input type="button" id="upload" name="upload" value="sure">
</form>
</body>
</html>
submit_form.js文件:
$(function(){
$("#upload").click(function(){
var jsonData = {
url:$("#url").val(),
type:"post",
data:{"otherdata":"otherdata-value"}, //也传递表单之外的参数
success:function(data){
alert(data);
}
};
$("#uploadForm").ajaxSubmit(jsonData);
});
});
servlet:
package com.study.form;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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;
/**
* Servlet implementation class StudyForm
*/
public class StudyForm extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
// request对象只能被组件解析一次。如果表单中的元素有文件路径, 文件。这种情况需要先获取路径才能接着操作文件,
// 可以在遍历List<FileItem>时,将路径和文件分别存到Map容器中,将其完全分离。 分开后在做操作
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
String savePath = "e:\\tmp\\test\\";
try {
if (ServletFileUpload.isMultipartContent(request)) {
List<FileItem> list = upload.parseRequest(request);
for (FileItem item : list) {
if (item.isFormField()) { // 普通的input框
// 获取当前变量input框的name属性值String
field = item.getFieldName();
//获取当前input框的值
String string = item.getString();
// 普通input框, 该方法返回null
String name = item.getName();
System.out.println();
}else { // type=file的input框String
fieldName = item.getFieldName();
if(fieldName != null && !"".equals(fieldName.trim())) {
InputStream in = null;
FileOutputStream out = null;
try {
// type=file的input框, 该方法返回上传文件的名称
String filename = item.getName();
if (filename == null || filename.trim().equals("")) {
continue;
}
in = item.getInputStream();
out = new FileOutputStream(savePath+filename);
byte buffer[] = new byte[1024];
int len = -1;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);out.flush();}
} finally {
in.close();
out.close();
item.delete();
}
}
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch
blocke.printStackTrace();
}finally {
}
}
}