自己就做了一个小例子(用servlet)如下:
up.jsp
<form action="/struts2/uploadServlet" method="post" enctype="multipart/form-data">
filename:<input type="text" name="name">
<br>
file1:<input type="file" name="file1"><br/>
file2:<input type="file" name="file2"><br>
<input type="submit" value="submit">
uploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory disk=new DiskFileItemFactory();//new一个磁盘文件条目工厂对象
String path=request.getRealPath("/upload");
disk.setRepository(new File(path));//设置临时文件
disk.setSizeThreshold(1024*1024);//设置放在内存中的最大容量,超过了则放置在临时文件里
ServletFileUpload upload=new ServletFileUpload(disk);//构造了一个上传文件的上传类
try {
List<FileItem> list=upload.parseRequest(request);
for(FileItem file:list){
if(file.isFormField()){//判断是否是除了file类型外的其他表单
String name=file.getFieldName();//得到简单类型表单的name
String value=file.getString("gbk");
System.out.println(name);//check!
request.setAttribute(name,value);
}else
{
String name=file.getFieldName();//得到file类型表单的name
System.out.println(name);
String value=file.getName();//得到表单里的值(就是那个全路径)
System.out.print(value);
//保证取得的名字是文件名,而不包括文件的路径
int tag=value.lastIndexOf("\\");
String filename=value.substring(tag+1);
System.out.println(filename);
request.setAttribute(name,filename);
//System.out.println("in servlet");//check!
file.write(new File(path,filename));
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("upload/MyJsp.jsp").forward(request,response);
}
获取表单名都是用getFileName()方法
这里最关键的是 是非file表单用getString("encoding")来获得表单的value
而file表单则用getName()方法来获取file表单的value (感觉这个方法取名不太合理啊!误导人啊!)
MyJsp.jsp
name:${requestScope.name}<br>
file:${requestScope.file1}<br>
file2:${requestScope.file2}<br>
转载于:https://my.oschina.net/joeyjava/blog/271555