创建工程后首先需要导入包
jsp-api.jar
jspsmartupload.jar
servlet-api.jar
将这三个包放入web-inf 下的lib中
然后就可以开始编写程序了
先是写一个表单的html,将form提交到action 的sevlet代码如下:
<!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>
然后编写servlet
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()提供了解决的方法