#JavaWeb文件上传
本博客是自我学习时对于知识的记忆可能并不适用了解思路就好
首先文件上传需要jar包
commons-fileupload
commons-io
servlet需要:
javax.servlet
javax.servlet.jsp
javaweb中在servlet类里来处里文件上传
而前端页面也需要用支持文件上传form表单中需要设置enctype值为multipart/form-data
####前端页面代码
<form method="post" enctype="multipart/form-data" action="">
上传用户:<input type="text" name="user"><br>
<input type="file" name="file">
<br>
<input type="submit" value="提交">
</form>
####servlet中代码
注:需要区分doget和dopost的使用场景(doGet会限制文件上传大小而doPost不会可以自己设置大小)
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//判断文件是否为普通表单还是带文件表单
if (!ServletFileUpload.isMultipartContent(req)) {
return;
}
//创建永久上传文件的保存路劲,建议的WEB-INF路劲下,用户无法访问 此处暂不使用优先使用临时路径
// String upload = this.getServletContext().getRealPath("/WEB-INF/upload");
// System.out.println(req.getServletContext().getContextPath());
// File uploadfile = new File(upload);
// if (!uploadfile.exists()) {
// uploadfile.mkdir();
// }
//创建临时上传文件的保存路劲,建议的WEB-INF路劲下,用户无法访问
String tempupload = this.getServletContext().getRealPath("/WEB-INF/tempupload");
File tempuploadfile = new File(tempupload);
if (!uploadfile.exists()) {
tempuploadfile.mkdir();
}
/*
* ServletFileUpload负责处理上传文件数据,会将表单中每个输入项封装为fileItem对象
* 该对象需要构造方法传入DiskFileFactory对象
* */
//1方法封装后面展示
//1. 创建DiskFileItemFactory对象处理文件上传路径或者大小限制
DiskFileItemFactory factory = mkDiskFileItemFactory(tempuploadfile);
//2方法封装后面展示
//2. 获取ServletFileUpload对象并设置限制
ServletFileUpload fileUpload = mkServletFileUpload(factory);
String msg;
try {
//3方法封装后面展示
//3.处理上传文件返回相应信息
msg = handleFile(fileUpload, req, tempuploadfile);
} catch (Exception e) {
throw new RuntimeException(e);
}
req.setAttribute("msg", msg);
req.getRequestDispatcher("info.jsp").forward(req, resp);
}
###封装代码
1. 创建DiskFileItemFactory对象处理文件上传路径或者大小限制
public static DiskFileItemFactory mkDiskFileItemFactory(File tempuploadfile){
//磁盘文件操作工厂,用来设置文件操作的缓冲区
DiskFileItemFactory factory=new DiskFileItemFactory();
//设置缓冲区大小
factory.setSizeThreshold(1024*1024);
//设置临时上传文件的路径
factory.setRepository(tempuploadfile);
return factory;
}
2. 获取ServletFileUpload对象并设置限制
public static ServletFileUpload mkServletFileUpload(DiskFileItemFactory factory){
//创建ServletFileUpload对象
ServletFileUpload fileUpload=new ServletFileUpload(factory);
//设置监听文件上传进度
fileUpload.setProgressListener(new ProgressListener() {
@Override
//l1为文件总共需要读取大小
//l为已经上传文件读取的大小
public void update(long l, long l1, int i) {
System.out.println("总大小:"+l1+" 已上传:"+l);
}
});
//设置编码格式
fileUpload.setHeaderEncoding("UTF-8");
//设置总文件大小限制
fileUpload.setSizeMax(1024*1024*10);
//设置单个文件上传大小限制
fileUpload.setFileSizeMax(1024*1024);
return fileUpload;
}
3.处理上传文件返回相应信息
public static String handleFile(ServletFileUpload fileUpload,HttpServletRequest req,File tempupload) throws Exception {
String msg="";
//获得item队列
List<FileItem> items=fileUpload.parseRequest(req);
//循环遍历
for (FileItem fileItem:items){
//判断是否为普通文件(true)还是文件表单
if (fileItem.isFormField()){
//获取jsp页面中的设置的属性名
String name=fileItem.getFieldName();
String value=fileItem.getString("UTF-8");
System.out.println(name+":"+value);
}else {
String uploadfilename=fileItem.getFieldName();
//判段文件名是否合法
if (uploadfilename.trim().equals("")||uploadfilename==null){
continue;
}
//获取文件名
String fileName=uploadfilename.substring(uploadfilename.lastIndexOf("/")+1);
//获取文件后缀名
String fileExName=uploadfilename.substring(uploadfilename.lastIndexOf(".")+1);
/*
* UUID(唯一识别的通用码),保证文件名唯一
* UUID.randomUUID()
* 网络传输需要文件序列化
* POJOl类需要用序列化
* */
String uripath=UUID.randomUUID().toString();
String RealPath=tempupload+"/"+uripath;
File realPathFile=new File(RealPath);
if (!realPathFile.exists()){
realPathFile.mkdir();
}
//通过Fileitem获取文件上传的流
InputStream is=fileItem.getInputStream();
//创建文件输出流
FileOutputStream fos=new FileOutputStream(realPathFile);
//创建缓冲区
byte[] buffer=new byte[1024*1024];
int len=0;
while((len=is.read(buffer))>=0){
fos.write(buffer,0,len);
}
fos.close();
is.close();
msg="文件上传成功";
fileItem.delete();
}
}
return msg;
}