<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"/>html
在tomcat的host目錄下設置,Context子標籤,讓上傳的時候,同步上傳到項目目錄下!!!java