问题
I try to upload a file (image) using Struts2. But, my file,file content and filename type have a null value ! I tried searching for this problem but without any result.
that is what I'm trying to do :
jsp :
<s:form id="registerSubmit" method="post" enctype="multipart/form-data" theme="bootstrap">
<s:textfield name="tel" cssClass="form-control" label="tel :"></s:textfield>
<label for="myFile">Upload your file</label>
<input type="file" name="file" />
<button type="submit" id="submit" > Enregistrer</button>
</s:form>
action :
public class Gestion extends ActionSupport implements SessionAware, ModelDriven{
private Visit c;
private Service Service;
private Long tel;
private File file;
private String fileContentType;
private String fileFileName;
public String addvisit(){
c = new visit();
Service = new ServiceImpl();
c.setTel(tel);
System.out.println(fileContentType); //null
System.out.println(fileFileName); //null
byte[] bFile = null;
if(file != null)
bFile = new byte[(int) file.length()];
c.setPhoto(bFile); // null
Service.add(c);
return "success";
}
//setters and getters
}
struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.multipart.maxSize" value="10000000" />
<package name="login" extends="struts-default" namespace="/">
<action name="addvisit" class="action.Gestion"
method="addvisit">
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/pjpeg
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success" type="json" >
<param name="root">map</param>
</result>
</action>
</package>
</struts>
回答1:
You are not pointing to your Action anywhere in your form.
I also suggest you to use (self closed) Struts Tags when possible:
<s:form action="addvisit" id="registerSubmit" method="post"
enctype="multipart/form-data" theme="bootstrap">
<s:textfield name="tel" cssClass="form-control" label="tel :" />
<s:file name="file" label="Upload your file" />
<s:submit id="submit" value="Enregistrer" />
</s:form>
That said, your error is 99% related to ModelDriven. Either remove the ModelDriven interface implementation, or configure the stack to have the FileUpload Interceptor after the ModelDriven one, like in the default stack (you are actually using two times the FileUpload interceptor):
<action name="addvisit" class="action.Gestion" method="addvisit">
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">2097152</param>
<param name="fileUpload.allowedTypes">
image/png,image/gif,image/jpeg,image/pjpeg
</param>
</interceptor-ref>
<result name="success" type="json" >
<param name="root">map</param>
</result>
</action>
来源:https://stackoverflow.com/questions/23779790/struts2-how-to-upload-file-using-intercepter