在实际的开发中在实现文件上传的同时肯定还有其他信息需要保存到数据库,就像混合表单在上传完毕之后需要将提交的基本信息插入数据库。
在这个demo中需要用到
这个架包来帮助实现
1.定义一个公共类实现文件上传(BaseServlet)
上传是一个公共的操作,可能在很多个servlet中都要涉及到上传,比如在Empservlet中要上传雇员的照片,在ManagerServlet中要上传管理员的照片,此时就需要将上传的操作定义到一个公共父类。
packagecom.sxt.mvcpro.servlet;importjava.io.File;importjava.io.UnsupportedEncodingException;importjava.lang.reflect.Field;importjava.text.ParseException;importjava.text.SimpleDateFormat;importjava.util.UUID;importjavax.servlet.ServletConfig;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importcom.jspsmart.upload.SmartUpload;
@SuppressWarnings("serial")public abstract class BaseServlet extendsHttpServlet {
SmartUpload smart= null;
String newFileName= null;public voidsaveFile(HttpServletRequest req, HttpServletResponse resp) {
smart= newSmartUpload();
ServletConfig config= super.getServletConfig();try{//初始化
smart.initialize(config, req, resp);
smart.setAllowedFilesList("jpg,png,gif");
smart.setMaxFileSize(1024 * 1024 * 1024 * 5);
smart.setTotalMaxFileSize(1024 * 1024 * 1024 * 5 * 10);
smart.upload();//取得上传文件的路径信息
String filepath = req.getServletContext().getRealPath("/" + this.getDir());
File file= newFile(filepath);if (!file.exists()) {
file.mkdirs();
}if (smart.getFiles().getFile(0).getSize() > 0) {//有文件才进行上传
String ext = smart.getFiles().getFile(0).getFileExt();//生成新的文件名
String fileName = UUID.randomUUID().toString().replaceAll("-", "");//保存文