如何在Struts动作中获取上传文件

时间:2015-07-02 12:20:56

标签: jsp servlets file-upload struts-1

这是上传文件的jsp页面:

<html:form action="/process.do?method=upload" method="post" enctype="multipart/form-data">       

     File :<input type="file" name="filename" /><br />

    <input type="submit" value="Upload File" style="margin: 40px 0 0 160px"/>

</html:form>

这是处理上传文件的动作转发方法:

public ActionForward upload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)  throws Exception 
     {
      System.out.println("Inside ProcessAction class upload method ");


    String filePath="";
     boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
     System.out.println("isMultipartContent -->>> "+isMultipartContent);
     FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> fields = upload.parseRequest(request);
                 System.out.println("file name -> "+request.getParameter("filename"));
                System.out.println("fields --> "+fields.size());

                 Iterator<FileItem> it = fields.iterator();
                while (it.hasNext()) {
                System.out.println("inside while -->>> ");
                    FileItem fileItem = it.next();
                    filePath = fileItem.getName();
                    System.out.println("inside while filePath -->>> "+filePath);
                }

            } catch (FileUploadException e) {
                e.printStackTrace();
            }
    System.out.println("filePath -->>> "+filePath);

}

输出:

  

Inside ProcessAction类上传方法
  isMultipartContent - &gt;&gt;真正
  文件名 - &gt;空
  领域-。 0
  filepath - &gt;&gt;&gt;

我无法抓取上传的文件路径。我正在从本地计算机上传文件到服务器。需要帮助

1 个答案:

答案 0 :(得分:0)

在struts 1中上传文件的方法更简单。您可以使用FormFile

对于用法,你可以看看 http://wiki.apache.org/struts/StrutsFileUpload