当表单被设置为multipart/form-data类型时,表单中的值post到服务端都是流的格式,此时拿不到参数值,需要通过对流的解析来获取。该问题有两种方法解决。
方法一:借助apache的common-fileupload组件来取得,具体代码参考如下。
JSP代码:
<html>
<body>
<!-- encType 必不可少 -->
<form action="upImgServlet" method="post" encType="multipart/form-data">
描述:
<input type="text" name="description"/><br/>选择图片:
<input type="file" name="img"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
FileUploadServlet代码:
public class FileUploadServlet extends HttpServlet {
public void destroy() {
(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
("text/html");
("UTF-8");
("UTF-8");
// 是一个开源包里的。
DiskFileUpload du = new DiskFileUpload();
(4194304); // 设置最大文件尺寸,这里是4MB
(4096);// 设置缓存区大小 ,4 kb;
// up 为 /WebRoot 下的 一个目录
(().getServletContext()
.getRealPath("/up"));// 设置缓存目录
// 得到所有文件
try {
List list = (request);
Iterator it = ();
while (()) {
fileItem = (FileItem) it
.next();
// 是否为表单元素。如文本框 等等。
if (()) {
String name = ();
//通过流 用来读取表单元素里的内容。
br = new BufferedReader(
new InputStreamReader(()));
//如果还有除文件域以外的其他表单元素 就用 if()进行名字一一匹配。此处就是的替换方法
if(("description")){
String contents = ();
System.out.println(contents);
}
}
// 文件域
else {
// 获得文件名,这个文件名包括路径:
String fileName = ();
int index = ('.');
fileName = (index);
fileName = this.getFileName() + fileName; //文件保存位置
(new File(().getServletContext().getRealPath("/img")+ "/" + fileName));
System.out.println("上传成功");
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
();
} catch (Exception e) {
// TODO Auto-generated catch block
();
}
PrintWriter out = ();
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
public void init() throws ServletException {
// Put your code here
}
// 以日期 获得一个文件名。(不重复);
String getFileName() {
cal = ();
int year = cal.get();
int mon = cal.get();
int day = cal.get();
int hour = cal.get();
int min = cal.get();
int sec = cal.get();
int mi = cal.get();
System.out.println("mon" + mon);
System.out.println("day" + day);
return "" + year + mon + day + hour + min + sec + mi;
}
}
方法二:这是一种更简单的方法,在jsp form提交时拦截submit方法,重置form的action属性将description作为url参数加入其中,这时该参数以get方式提交后台servlet就可以取的到了。