用commons组件实现上传
<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%
DiskFileUpload dfu = new DiskFileUpload();
// 设置允许用户上传文件大小,单位:字节
dfu.setSizeMax(10000000);
// 设置最多只允许在内存中存储的数据,单位:字节
dfu.setSizeThreshold(4096);
// 设置一个文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
//String strURL = new java.io.File(application.getRealPath(request.getRequestURI())).getParent();
String xiangmumingcheng = (String) session.getAttribute("xiangmumingcheng");
String f_gonggao = "image"; //设定文件夹名称
String m_path = request.getRealPath("/") + f_gonggao + "\\";
java.io.File r_path = new java.io.File(m_path);
if (!r_path.exists()) {
r_path.mkdir();
}
String strURL = m_path;
// System.out.println("路径名" + strURL);
dfu.setRepositoryPath(strURL);
//开始读取上传信息
try {
List fileItems = dfu.parseRequest(request);
//依次处理每个上传的文件
Iterator i = fileItems.iterator();
String n a m e = null;//这里的n a m e其实是name 但是在博客里不正常显示所以就这么写了
long size = 0;
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
//忽略其他不是文件域的所有表单信息
if (!fi.isFormField()) {
name = fi.getName();
size = fi.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
}
>
size = fi.getSize();
name = name.replace(':', '_');
name = name.replace('\\', '_');
File writeFile = new File(strURL, name);
String shangchuanlujing = f_gonggao + "\\" + name;
//System.out.println("上传路径" + shangchuanlujing);
fi.write(writeFile);
}
} catch (FileUploadException fue){
fue.printStackTrace();
//response.sendRedirect("ErrorPage.jsp");
}
%>