如何在struts2中读取上传的文件?
我正在开发一个网络应用程序,当我上传文件时我有一些问题:我可以上传我需要的文件类型 喜欢:我可以上传和阅读图片但我上传他时无法读取其他文件
这是我的jsp文件:
<s:form action="fileUpload" method="post" enctype="multipart/form-data">
<s:file name="toBeUploaded" label="Choose file to upload" />
<s:submit value="upload" align="center"/>
</s:form>
行动类:
public class FileUploadAction extends ActionSupport implements ServletRequestAware {
public File toBeUploaded;
public String toBeUploadedFileName;
public String toBeUploadedContentType;
private HttpServletRequest servletRequest;
public String execute() {
String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
System.out.println("Server path:" + filePath);
File fileToCreate = new File(filePath, this.toBeUploadedFileName);
try {
FileUtils.copyFile(this.toBeUploaded, fileToCreate);
FileUtils.copyFile(toBeUploaded, fileToCreate);
} catch (IOException e) {
// TODO Auto-generated catch block
addActionError(e.getMessage());
}
return SUCCESS;
} + getters/setters
<action name="fileUpload" class="com.ged.control.FileUploadAction">
<interceptor-ref name="basicStack"/>
<interceptor-ref name="fileUpload">
<param name="maximumSize">9999999999</param>
<param name="allowedTypes">image/gif,image/jpeg,image/png,application/msword,
application/mspowerpoint,text/doc,text/plain,application/pdf,application/ms-excel,application/xml,application/powerpoint,audio/mpeg3,audio/x-mpeg-3,video/mpeg,video/x-mpeg,audio/wav,application/x-mspowerpoint,application/vnd.ms-excel,video/avi</param>
</interceptor-ref>
<interceptor-ref name="validation"/>
<interceptor-ref name="workflow"/>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">/uploadSucceed.jsp</result>
<result name="input">/fileUpload.jsp</result>
</action>
结果页面:
<article class="module width_full">
<header><h3>Post New section</h3></header>
File Name : <s:property value="toBeUploadedFileName"></s:property>
<br/>
Content type: <s:property value="toBeUploadedContentType" ></s:property>
<br/>
User file :<s:property value="toBeUploaded"></s:property>
<br/>
Uploaded file:
<br/>
<img src="<s:property value="toBeUploadedFileName"/>" ></img>
</article>
答案 0 :(得分:0)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default" namespace="/">
<action name="fileUpload" class="com.pkg.FileUploadAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">1048576</param>
<param name="allowedTypes">
<!-- it will allow to upload any file image/png,image/gif,image/jpeg,image/`enter code here`jpeg -->
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">uploadSucceed.jsp</result>
<result name="input">fileUpload.jsp</result>
</action>
</package>
</struts>