package org.accp.ch12.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
public class UploadServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public UploadServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
//上传初始化
su.initialize(getServletConfig(),request,response);
// 设定上传限制
//1.限制每个上传文件的最大长度。
su.setMaxFileSize(10000000);
//2.限制总上传数据的长度。
su.setTotalMaxFileSize(20000000);
//3.设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。
su.setAllowedFilesList("doc,txt,jpg,rar,mid,waw,mp3,gif");
//4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有扩展名的文件。
try {
su.setDeniedFilesList("exe,bat,jsp,htm,html");
//上传文件[取得上传的文件数据]
su.upload();
//取表单元素的文本信息
//su.getRequest().getParameter("desc");
System.out.println("<p style='color:orange;'>描述信息:"+su.getRequest().getParameter("desc")+"</p>");
//将上传文件保存到指定目录
//动态获得服务器项目的路径[文件上传后的保存路径]
String path = getServletContext().getRealPath("/")+"\\userfiles";
java.io.File dir = new java.io.File(path);
if (!dir.exists())//如果目录不存在则创建
dir.mkdirs();
for(int i=0; i< su.getFiles().getCount(); i++){
File upfile = su.getFiles().getFile(i);//得到当前上传的这份文件
Calendar cal = Calendar.getInstance();
String filepath = path+"\\"+cal.get(Calendar.YEAR)+"_"+
cal.get(Calendar.MONTH)+"_"+
cal.get(Calendar.DATE)+"_"+
cal.get(Calendar.HOUR)+"_"+
cal.get(Calendar.MINUTE)+"_"+
cal.get(Calendar.SECOND)+"_"+
cal.get(Calendar.MILLISECOND)+"."+
upfile.getFileExt();
//su.save(path+"将文件保存到目录但是不改变文件名[使用物理路径]
upfile.saveAs(filepath);//使用File类自身的方法完成保存
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}