import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
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;
public class SmartUploadFile extends HttpServlet {
/**
* 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 {
/*获取文件存储路径*/
String filePath = getServletContext().getRealPath("/") + "images";
File file = new File(filePath);
if(!file.exists()){
file.mkdir();
}
/*上传文件*/
SmartUpload smartUpload = new SmartUpload();
smartUpload.initialize(getServletConfig(), request, response);
smartUpload.setMaxFileSize(1024*1024*10);
smartUpload.setTotalMaxFileSize(1024*1024*100);
smartUpload.setAllowedFilesList("txt,jpg,gif,png");
int fileCount =0;//上传文件的数量
try {
smartUpload.setDeniedFilesList("rar,jsp,js");
smartUpload.upload();
for(int i=0;i<smartUpload.getFiles().getCount();i++)
{
com.jspsmart.upload.File f= smartUpload.getFiles().getFile(i);
String ext = f.getFileExt(); // 文件名后缀
if (f.isMissing()) continue; //如果没有上传文件,就跳过
f.saveAs(filePath+File.separator+System.currentTimeMillis()+"."+ext); //以新文件名存储
System.out.println("上传文件"+System.currentTimeMillis()+i+"."+ext);
fileCount++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*获取普通表单域*/
String username = smartUpload.getRequest().getParameter("username");
System.out.println("用户名:"+username);
request.setAttribute("responseStr",fileCount);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}