日期:2014-05-16 浏览次数:20379 次
工具类源程序:
package com.mobile.utils; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jspsmart.upload.File; import com.jspsmart.upload.Files; import com.jspsmart.upload.SmartUpload; public class FilesUpload { public static boolean upload(ServletConfig config, HttpServletRequest request, HttpServletResponse response) { boolean flag = false; // 声明一个SmartUpload对象 SmartUpload su = new SmartUpload(); try { // 传入相关参数,完成smartupload初始化 su.initialize(config, request, response); // 上传文件 // 限定上传文件的类型 su.setAllowedFilesList("txt"); // 相当于读取文件流 su.upload(); Files files = su.getFiles(); int count = files.getCount(); // 循环对每一个文件进行处理 for (int i = 0; i < count; i++) { // 得到每一个文件 File f = files.getFile(i); if (!f.isMissing()) { f.saveAs("./upload/" + f.getFileName(), File.SAVEAS_VIRTUAL); } } flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } }
?jsp页面源程序如下:
<%@ page contentType="text/html;charset=GBK"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'upload.jsp' starting page</title> </head> <body> <form action="UploadServlet" encType="multipart/form-data" method="post"> 请选择附件: <br> <input type="file" name="myfile"> <br> <input type="file" name="myfile"> <br> <input type="file" name="myfile"> <br> <input type="submit" value="立即上传"> </form> </body> </html>
??在Servlet中只需简单调用一下即可:
boolean flag = FilesUpload.upload(this.getServletConfig(), request, response); if (flag) { response.getWriter().print("成功上传文件!"); }
?