fileUpload是apache的commons组件所提供的上传部件,它最重要的工作是帮助我们解析request.getInpustream()。可以参考一下线上API文本文档:
http://tool.oschina.net/apidocs/apidoc?api=commons-fileupload

1. DiskFileItemFactory
构造器
1) DiskFileItemFactory() // 应用默认设置配备
2) DiskFileItemFactory(int sizeThreshold, File repository)
sizeThreshold 内存缓冲区, 不可以设定很大, 不然也会导致JVM奔溃
repository 临时性文件名称
2. ServletFileUpload
1) isMutipartContent(request) // 分辨上传表格是否属于multipart/form-data类型 true/false
2) parseRequest(request) // 解析request, 传参为List
3) isFormField() //是不是一般文档
4) setFileSizeMax(long) // 上传文档单独最大值 fileupload内部结构根据抛出异常的方式解决, 解决图片大小超过限定, 能通过捕捉这一出现异常, 提醒给消费者
5) setSizeMax(long) // 上传文档总产量最大值
6) setHeaderEncoding(String) // 设定编码方式
1.导进jar包

2.撰写jsp

3.撰写servlet
//建立业务层目标
NewsService newsService = new NewsService();
InputStream in = null;
OutputStream out = null;
int id = 0;//网页页面传出的cd值
//建立解析器工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//获得解析器
ServletFileUpload upload = new ServletFileUpload(factory);
// 上传表格是否属于multipart/form-data类型
if(!upload.isMultipartContent(request)){
return ;
}
//解析request的输入流
try{
List
//迭代更新list
for(FileItem f:parseRequest){
if(f.isFormField()){
//一般字段名
id = Integer.parseInt(f.getFieldName());
String value = f.getString();
System.out.println(“name” ”=” value);
}else{
//上传文档
//获得上传文件夹名称
String name = f.getName();
System.out.println(“文件夹名称” name);
name = name.substring(name.lastIndexOf(“”) 1);
System.out.println(name);
//获得输入流
in = f.getInputStream();
//获得上传文件路径
String savePath = “D:workspacedt91FileUpLoadTestDemoWebContentimages” name;
//上传文件夹名称若不会有, 则先建立
File path = new File(savePath);
if(!path.exists()){
path.getParentFile().mkdir();
}
//获得输出流
out = new FileOutputStream(path);
int len = 0;
byte[]b = new byte[1024];
while((len = in.read(b)) > 0){
out.write(b,0,len);
}
System.out.println(“上传取得成功”);
//储存到数据库系统
int count = newsService.saveUrl(name, id);
if(count > 0 ){
System.out.println(“途径保存成功”);
}else{
System.out.println(“途径保存失败”);
}
}
}
}catch (FileUploadException e){
// TODO Auto-generated catch block
System.out.println(“上传不成功”);
e.printStackTrace();
}finally{
if(in != null){
in.close();
}
if(out != null){
out.close();
}
}
原创文章,作者:leping,如若转载,请注明出处:https://www.qlhjjj.com/biao-3240.html