<form action="UploadServlet" enctype="multipart/form-data" method="post"> 书籍名称:<input type="text"name="name"><br> 图片名称:上传文件:<input type="file" name="img"><br/> <input type="submit"value="提交"> </form>
package web; import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.PageContext; import com.jspsmart.upload.Request; import com.jspsmart.upload.SmartUpload; import com.jspsmart.upload.SmartUploadException; public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); //实例化SmartUpload上传组件 SmartUpload smart = new SmartUpload(); //PageContext pageContext=JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, true, 8192, true); //初始化上传操作 smart.initialize(this.getServletConfig(),req,resp); smart.setMaxFileSize(1024*1024*10); smart.setAllowedFilesList("jpg,jpeg,bmp"); //设置字符集 smart.setCharset("gbk"); //准备上传 try { smart.setDeniedFilesList("exe,jsp,bat,html,,"); smart.upload(); Long time=new Date().getTime(); String ext=smart.getFiles().getFile(0).getFileExt();//获取文件后缀 String filename=time+"."+ext; //smart.getFiles().getFile(0).saveAs( "/img/ "+filename);//保存在容器目录下 String pa=this.getServletContext().getRealPath("/")+"img"+java.io.File.separator+filename; System.out.println(pa); smart.getFiles().getFile(0).saveAs(pa); // smart.save("img"); Request smartReq =smart.getRequest(); String name=smartReq.getParameter("name"); resp.getWriter().println(name); } catch (Exception e) { e.printStackTrace(); } //将上传的文件保存到项目根路径下的uploadfile目录中 } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } }
<Context path="/web" docBase="D:\updemo\WebRoot"/>
在tomcat的host目录下设置,Context子标签,让上传的时候,同步上传到项目目录下!!!