package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.*;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class UploadFile extends HttpServlet {
public UploadFile() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
SmartUpload mySmartUpload = new SmartUpload();
//初始化操作
mySmartUpload.initialize(this.getServletConfig(), request,response);
String currentDirectoryPath=null;
String savePath="d:/";
//mySmartUpload.setDenyPhysicalPath(true);
mySmartUpload.setForcePhysicalPath(true);
// 设定上传限制
// 1.限制每个上传文件的最大长度。10M
mySmartUpload.setMaxFileSize(10000000);
// 2.限制总上传数据的长度。
mySmartUpload.setTotalMaxFileSize(20000000);
// 3.设定允许上传的文件(通过扩展名限制),这里仅允许doc,txt文件。
mySmartUpload.setAllowedFilesList("doc,txt");
try {
// 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat, jsp,htm,html扩展名的文件和没有扩展名的文件。
mySmartUpload.setDeniedFilesList("exe,bat,jsp,htm,html,,");
} catch (Exception e) {
e.printStackTrace();
}
//上传操作
try {
mySmartUpload.upload();
} catch (SmartUploadException e1) {
e1.printStackTrace();
}
try {
// 将上传文件保存到指定目录
int count = mySmartUpload.save(savePath);
System.out.println(count + "个文件已上传!");
} catch (Exception e) {
e.printStackTrace();
}
//读取其它数据
com.jspsmart.upload.SmartRequest req = mySmartUpload.getRequest();
//保存文件
for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
com.jspsmart.upload.SmartFile file = mySmartUpload.getFiles().getFile(i);
if (file.isMissing()) {
continue;
}
//显示当前文件信息
out.println("<table border=1>");
out.println("<tr><td>表单项名(FiledName)</td><td>"+file.getFieldName()+"</tr></tr>");
out.println("<tr><td>文件长度(Size)</td><td>"+file.getSize()+"</td><td>");
out.println("<tr><td>文件名(FileName)</td><td>"+file.getFileName()+"</tr></tr>");
out.println("<tr><td>文件扩展名(FiledExt)</td><td>"+file.getFileExt()+"</tr></tr>");
out.println("<tr><td>文件全名(FiledPathName)</td><td>"+file.getFilePathName()+"</tr></tr>");
out.println("</table><br>");
out.println("文件名称:"+file.getFileName());
}
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
public void init() throws ServletException {
}
}