我尝试使用Struts2上传文件(图像)。但是,我的文件,文件内容和文件名类型都是空值! 我试着搜索这个问题,但没有任何结果。
这就是我想要做的事情:
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>
行动:
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>
答案 0 :(得分:1)
您没有在表单中的任何位置指向您的操作。
我还建议你尽可能使用(自闭)Struts标签:
<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>
那就是说,你的错误与ModelDriven有99%的关系。删除ModelDriven接口实现,或者将堆栈配置为在 ModelDriven之后具有FileUpload Interceptor ,就像在默认堆栈中一样(实际上使用的是FileUpload拦截器的两倍):
<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>