文件上传
原理: 我们在提交文本的时候,其实就是将文本以字符串上传
所以文件上传也就是将文件以字节码的形式上传
1.upload.jsp
在upload.jsp中创建一个上传表单
<!--
只要是上传,method必须是post;
enctype为"mutipart/form-data"(多段表单数据)
-->
<form action="<c:url value='file/upload'></c:url>" method="post" enctype="multipart/form-data">
<!--这里的name必须对应action中的File name(也就是请求参数,如果是文本是String类型的对应文件名,这里是文件就是File类型的对应文件名)-->
<input type="file" name="mine">
<input type="submit" value="上传">
</form>
2.upload.action
private File mine;//这里的文件对象就是你上传的那个文件(注意对应请求参数name)
private String mineFileName;//这里就是文件名
//注意属性生成set,get方法,这样struts2会自动将文件及文件名封装到对应的对象中
public String upload() throws IOException {
//实例化一个空文件对象,文件名为上传时的文件名
File file = new File("D:/upload",mineFileName);
//将你上传的文件复制到了D:/upload/mineFileName空文件中
FileUtils.copyFile(mine, file);
//将文件名put到session中以便下载时获取文件名
ActionContext.getContext().getSession().put("mineFileName", mineFileName);
return "success";
}
3.struts.xml
<package name="file" extends="struts-default" namespace="/file">
<action name="*" class="com.me.file.action.FileAction" method="{1}">
<result name="success">success.jsp</result>
</action>
</package>
上传完毕,即可在相应目录看到文件
success.jsp(下载页面):
<a href="<c:url value='file/download'></c:url>">下载</a>
<a href="<c:url value='file/preview'></c:url>">预览</a>
文件下载(预览)
1.success.jsp
<a href="<c:url value='file/download'></c:url>">下载</a>
<a href="<c:url value='file/preview'></c:url>">预览</a>
2.actions
public String download(){
return "down";
}
public String preview(){
return "pre";
}
//注意这里的getMineFile()的MineFile必须与struts.xml中配置的inputName一致(mineFile)
public InputStream getMineFile() throws FileNotFoundException{
//获取上传的文件名
mineFileName = ActionContext.getContext().getSession().get("mineFileName").toString();
//获取下载的文件输入流,文件来自D:/upload/mineFileName
FileInputStream fis = new FileInputStream("D:/upload/" + mineFileName);
//返回这个输入流
return fis;
}
3.struts.xml
<package name="file" extends="struts-default" namespace="/file">
<action name="*" class="com.me.file.action.FileAction" method="{1}">
<!--下载返回的是一个流-->
<result name="down" type="stream">
<!--inputName为输入流方法中的getXXX中的xXX(首字母小写)-->
<param name="inputName">mineFile</param>
<!--
contentDisposition(内容安排)为attachment(附件,这样浏览器知道你是要下载附件)
filename为下载时下载框中的文件名(这里获取的是session中的那个文件名,也就是上传的文件名)
-->
<param name="contentDisposition">attachment; filename=${mineFileName}</param>
</result>
<result name="pre" type="stream">
<param name="inputName">mineFile</param>
<!--预览这里没有设置 内容安排 为附件,所以浏览器就直接预览这个文件-->
<param name="contentDisposition">filename=${mineFileName}</param>
</result>
</action>
</package>
struts2封装好的关于文件的属性:
注:xxx为请求参数名
1.String xxxFileName
文件名
2.String xxxContentType
文件类型
3.File xxx
文件