欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

文件上传功能

程序员文章站 2022-03-01 17:40:20
...

1.表单必须这样写:

<form name="wzBaiscBusiForm" method="post" enctype="multipart/form-data" action="">

 

2.Action中的处理代码

MultiPartRequestWrapper req = (MultiPartRequestWrapper) ServletActionContext.getRequest();
  String attmNumber = "";
  Enumeration enu = req.getFileParameterNames();
  String realpath = Config.getInstance().getValue("..."); // 附件存放路径
   while (enu.hasMoreElements()) { // 对每一个文件域进行遍历
   String controlName = (String) enu.nextElement();
   String[] fileNames = req.getFileNames(controlName);
   File[] uploadFiles = req.getFiles(controlName);
   for (int i = 0; i < uploadFiles.length; i++) {
    // 创建文件夹,将文件保存到目录
    File dir = new File(req.getRealPath("/") + realpath + "/");
    if (!dir.exists())
     dir.mkdir();
    File uploadFile = uploadFiles[i];
    File file = new File(req.getRealPath("/") + realpath + "/"
      + fileNames[i]);
    byte[] data = new byte[8192];
    int byteRead = -1;
    FileInputStream in = new FileInputStream(uploadFile);
    FileOutputStream out = new FileOutputStream(file);
    while ((byteRead = in.read(data)) != -1) {
     out.write(data, 0, byteRead);
     out.flush();
    }
    out.close();
    in.close();
   }