建立工程后首先须要导入包html
jsp-api.jarjava
jspsmartupload.jarweb
servlet-api.jarapi
将这三个包放入web-inf 下的lib中jsp
而后就能够开始编写程序了post
先是写一个表单的html,将form提交到action 的sevlet代码以下:this
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="action" method="post" enctype="multipart/form-data"> <input type = "file" name="file"> <input type = "file" name="file"> <input type="submit" value="提交"> </form> </body> </html>
而后编写servletspa
package com.test; import java.io.File; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jspsmart.upload.SmartUpload; import com.jspsmart.upload.SmartUploadException; /** * Servlet implementation class action */ @WebServlet("/action") public class action extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public action() { super(); // TODO Auto-generated constructor stub } /** * @see Servlet#init(ServletConfig) */ /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub SmartUpload smart = new SmartUpload();//新建servlet smart.initialize(this.getServletConfig(), request, response);//初始化servlet try { smart.upload();//上传准备 String path="d:"+File.separator+"testDocument"; smart.save(path);//文件保存 } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
此外还有一些要注意的,由于封装了form表单,getparameter将取不到值,不过smartupload()提供了解决的方法code