首页>代码>java servlet通过SmartUpload开发文件批量上传、批量下载源码分享>/fileBatchWithSmart/src/org/shengke/servlet/SmartUploadServlet.java
package org.shengke.servlet; import java.io.File; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jspsmart.upload.SmartUpload; /** * 文件批量上传 */ public class SmartUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doPost(req,resp); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //设置上传文件保存路径 // String filePath = getServletContext().getRealPath("/") + "images"; String filePath = "/home/shengke/workspace/wenjianSCXZ/WebContent/images"; File file = new File(filePath); //这个应该都知道把,如果路径不存在,就创建它,注意权限问题 if(!file.exists()){ file.mkdir(); } //下面就是使用Smart组建实现批量上传 SmartUpload su = new SmartUpload(); //初始化对象 su.initialize(getServletConfig(), req, resp); //设置上传文件大小 su.setMaxFileSize(1024*1024*10); //设置所有文件的大小 su.setTotalMaxFileSize(1024*1024*100); //设置允许上传文件类型 su.setAllowedFilesList("txt,jpg,gif"); String result = "上传成功!"; //设置禁止上传的文件类型 try { //和setAllowedFilesList是相对的,一般项目保留一个就可以满足需求 su.setDeniedFilesList("rar,jsp,js"); //上传文件 su.upload(); int count = su.save(filePath); System.out.println("上传成功" + count + "个文件!"); } catch (Exception e) { result = "上传失败!"; //对异常作出不同的提示,如果感兴趣的话,可以 测试一下异常代号 if(e.getMessage().indexOf("1015")!=-1){ result = "上传失败:上传文件类型不正确!"; }else if(e.getMessage().indexOf("1010")!=-1){ result = "上传失败:上传文件类型不正确!"; }else if(e.getMessage().indexOf("1105")!=-1){ result = "上传失败:上传文件大小超出单个文件最大值!"; }else if(e.getMessage().indexOf("1110")!=-1){ result = "上传失败:上传文件总大小超出总文件最大值!"; } e.printStackTrace(); } //控制台输出上传文件的信息,供君使用 for(int i =0; i < su.getFiles().getCount(); i++){ com.jspsmart.upload.File tempFile = su.getFiles().getFile(i); System.out.println("---------------------------"); System.out.println("表单当中name属性值:" + tempFile.getFieldName()); System.out.println("上传文件名:" + tempFile.getFieldName()); System.out.println("上传文件长度:" + tempFile.getSize()); System.out.println("上传文件的拓展名:" + tempFile.getFileExt()); System.out.println("上传文件的全名:" + tempFile.getFilePathName()); System.out.println("---------------------------"); } //跳转页,把result带过去 req.setAttribute("result", result); req.getRequestDispatcher("jsp/02.jsp").forward(req, resp); } }