multipart/form-data提交的表单,里面包含了表单和二进制数据,不能用一般方法解析。解这里用到fileupload框架。需要导入commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar。
这里给出了具体servlet代码,这是一个受到App上传的图片如何保存的代码
private void getfile(HttpServletRequest req){
//设置工厂
DiskFileItemFactory factory=new DiskFileItemFactory();
//设置缓冲区大小5M
//factory.setSizeThreshold(1024*1024*5);
//设置临时文件
//factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//设置解析器
ServletFileUpload sUpload=new ServletFileUpload(factory);
try {
//解析结果放list
List<FileItem> list=sUpload.parseRequest(req);
System.out.println("表单数据项数:"+list.size());
for(FileItem item:list){
String name=item.getFieldName();
System.out.println("数据项名:"+name);
InputStream in=item.getInputStream();
//提交的表单中,文件键值为aFile
if(name.equals("aFile")){
//保存文件
//最好保存在绝对路径
System.out.println(item.getName());
//String path=this.getServletConfig().getServletContext().getRealPath("/");
//path=path+"\\images\\test2.png";
String path="d://test1.png";
System.out.println(path);
File file=new File(path);
BufferedInputStream fi = new BufferedInputStream(in);
FileOutputStream fo = new FileOutputStream(file);
int f;
while ((f=fi.read())!=-1) {
fo.write(f);
}
fo.flush();
fo.close();
fi.close();
}else {
System.out.println("一般表单"+item.getName()+","
+item.getString());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}