1.如果不存在,创建文件保存目录
package upUtil;
import java.io.File;
public class FileUitl
{
public static void createDirectory(String path)
{
File file= new File(path);
if (!file.exists()) {
file.mkdirs();
}
}
}
2.创建上传页面 fileup.jsp
上传文件名:
file:
3.上传文件的servlet
package servlet;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UpLoadServelet extends HttpServlet {
private String context = "";//项目所在目录
public void init() throws ServletException {
//得到项目所在目录
context=this.getServletConfig().getServletContext().getRealPath("/upload");
}
public UpLoadServelet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
String timeValue = df.format(new Date());
String path = context + "\\" + timeValue;
File file = new File(path);
if (!file.exists()){
// 判断文件夹是否存在,如果不存在则创建文件夹
file.mkdirs();
}
// 1、创建工厂
DiskFileItemFactory fcatory = new DiskFileItemFactory();
// 2、设置属性
fcatory.setRepository(new File(path)); // 1、设置文件上传过程中的临时存储目录
fcatory.setSizeThreshold(1024 * 1024); // 2、设置大小(默认为10240),当文件超出时,先存入临时存储目录
// 3、创建文件上传实例
ServletFileUpload upload = new ServletFileUpload(fcatory);
String fileName = "";
try
{
List list = upload.parseRequest(request); // 获得文件或表单数据
for (FileItem fileItem : list) {
String name = fileItem.getFieldName(); // 得到name
if (fileItem.isFormField()) // 判断fileItem是否为普通的表单值
{
String value = fileItem.getString("utf-8"); // 普通的表单得到名字value
request.setAttribute(name, value);
}
else{
String valueName = fileItem.getName(); // 获得文件的名字
int start = valueName.lastIndexOf("\\");
fileName = valueName.substring(start + 1);
request.setAttribute(name, fileName);
//将文件写入到path目录下
fileItem.write(new File(path, fileName));
}
}
}
catch (Exception e)
{
//e.printStackTrace();
}
path += "\\" + fileName;
System.out.println(path);
request.setAttribute("path", path);
request.getRequestDispatcher("result.jsp").forward(request,response);
}
}