文件批量上传

xiaoxiao2024-04-13  25

执行类:

/** * @author LXY * @date 2008=11-11 */public class UploadAction extends HttpServlet { private static final long serialVersionUID = 1L; String uploadPath = ""; // 用于存放上传文件的目录 String tempPath = ""; // 用于存放临时文件的目录

 @Override public void init() throws ServletException {  super.init();  //从配置文件中读取文件路径  uploadPath = this.getInitParameter("uploadPath");  tempPath = this.getInitParameter("tempPath"); }

 @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {

  //用于存放上传文件的原路径  List<String> fileList = new ArrayList<String>();  //创建存放上传文件的文件夹  File fileDir = new File(uploadPath);  if (!fileDir.exists()) {   fileDir.mkdir();  }  //创建临时文件夹  File tempDir = new File(tempPath);  if (!tempDir.exists()) {   tempDir.mkdir();  }  DiskFileItemFactory factory = new DiskFileItemFactory();  factory.setRepository(new File(tempPath)); // 设置临时目录  factory.setSizeThreshold(1024 * 1024); // 设置缓冲区大小

  ServletFileUpload upload = new ServletFileUpload(factory);  //设置字符集  upload.setHeaderEncoding("UTF-8");  try {   List<FileItem> list = upload.parseRequest(request); // 得到所有的文件

   for (FileItem fileItem : list) {    // 如果是表单信息    if (fileItem.isFormField()) {     String name = fileItem.getFieldName(); // 获得表单中按钮的类型     String value = fileItem.getString("UTF-8"); // 获得表单中按钮的值     request.setAttribute(name, value);    } else {     String name = fileItem.getFieldName(); //获得表单中域的名字     String value = fileItem.getName(); // 获得从浏览器中取得的文件全路径     //将上传文件的路径放到列表里     fileList.add(value);     int start = value.lastIndexOf("\\");     String fileName = value.substring(start + 1); // 由于不同的浏览器可能取得的文件的名字不同,有的浏览器将整个路径取道,有的浏览器只取到文件名     request.setAttribute(name, fileName); // IE里取的是文件明,如XXX.doc等

     // 使用fileupload提供的上传     try {      // 写入文件,也可以从fileName中提取文件名:      fileItem.write(new File(uploadPath, fileName));     } catch (Exception e) {      e.printStackTrace();     }    }   }  } catch (FileUploadException e) {   e.printStackTrace();  }  //将获得的文件路径放回请求  request.setAttribute("fileList", fileList);  //页面跳转  request.getRequestDispatcher("success.jsp").forward(request, response); }

}

转载请注明原文地址: https://www.6miu.com/read-5014957.html

最新回复(0)