分享fileupload获取文件路径 fileupload控件上传文章

一、什么是fileUpload?
fileUpload是apache的commons组件提供的上传组件 , 它最主要的工作就是帮我们解析request.getInpustream() 。可以参考在线API文档:
http://www.jinnalai.com/uploads/article/2021/09/29/87132 class=wp-block-image>

分享fileupload获取文件路径 fileupload控件上传文章

文章插图
【分享fileupload获取文件路径 fileupload控件上传文章】三、fileupload核心API
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<FileItem>类型
3) isFormField() //是否是普通文件
4) setFileSizeMax(long) // 上传文件单个最大值 fileupload内部通过抛出异常的形式处理, 处理文件大小超出限制, 可以通过捕获这个异常, 提示给用户
5) setSizeMax(long) // 上传文件总量最大值
6) setHeaderEncoding(String) // 设置编码格式
四、实现过程
1.导入jar包

分享fileupload获取文件路径 fileupload控件上传文章

文章插图
2.编写jsp

分享fileupload获取文件路径 fileupload控件上传文章

文章插图
3.编写servlet
//创建业务层对象
NewsService newsService = new NewsService();
InputStream in = null;
OutputStream out = null;
int id = 0;//页面传来的id值
//创建解析器工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//获取解析器
ServletFileUpload upload = new ServletFileUpload(factory);
// 上传表单是否为multipart/form-data类型
if(!upload.isMultipartContent(request)) {
return ;
}
//解析request的输入流
try {
List<FileItem> parseRequest = upload.parseRequest(request);
//迭代list
for(FileItem f:parseRequest) {
if(f.isFormField()) {
//普通字段
id = Integer.parseInt(f.getFieldName());
String value = https://www.jinnalai.com/fenxiang/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:\workspacedt91\FileUpLoadTestDemo\WebContent\images\”+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();
}
}

    推荐阅读