struts2文件上传file,contentType,fileName出现null

用struts2文件上传,查看文档

The fileUpload interceptor will use setter injection to insert the uploaded file and related data into your Action class. For a form field named upload you would provide the three setter methods shown in the following example:

The purpose of each one of these methods is described in the table below. Notice that if you have multiple file form elements with different names you would be required to have another corresponding set of these methods for each file uploaded.

Method Signature Description
setX(File file) The file that contains the content of the uploaded file. This is a temporary file and file.getName() will not return the original name of the file
setXContentType(String contentType) The mime type of the uploaded file
setXFileName(String fileName) The actual file name of the uploaded file (not the HTML name)

注意上面的X,代表文件名

也就是说如果是

"doUpload" method="post" enctype="multipart/form-data">
    "upload" label="File"/>
    

那么
 
  

Example Action class:

package com.example;

   import java.io.File;
   import com.opensymphony.xwork2.ActionSupport;

   public class UploadAction extends ActionSupport {
      private File upload;
      private String uploadContentType;
      private String uploadFileName;

      public void setUpload(File file) {
         this.file = file;
      }

      public void setUploadContentType(String contentType) {
         this.contentType = contentType;
      }

      public void setUploadFileName(String filename) {
         this.filename = filename;
      }

      public String execute() {
         //...
         return SUCCESS;
      }
 }
而且要必须注意属性的大小写,否则会出现Null
private File upload; private String uploadContentType; private String uploadFileName;
如果你写成文档上面的
package com.example;

   import java.io.File;
   import com.opensymphony.xwork2.ActionSupport;

   public class UploadAction extends ActionSupport {
      private File file;
      private String contentType;
      private String filename;

      public void setUpload(File file) {
         this.file = file;
      }

      public void setUploadContentType(String contentType) {
         this.contentType = contentType;
      }

      public void setUploadFileName(String filename) {
         this.filename = filename;
      }

      public String execute() {
         //...
         return SUCCESS;
      }
 }
就会出现null(注意加上X代表表单type=file的name值)

你可能感兴趣的:(Struts2)