分为三部分:一:jsp 二:action 三:struts配置。
一:upload.jsp
1.表单三要素:1.提交方式post 2.enctype类型:multipart/form-data 3.type=file
关键代码实现:
<body>
<form action="${pageContext.request.contextPath }/upload/upload.action" method="post" enctype="multipart/form-data">
文件:<input type="file" name="attach" /><br>
描述:<input type="text" name="info"/><br/>
<input type="submit" value="上传"/>
<input type="submit" value="下载"/>
</form>
</body>
其中name=“”attach”是固定的。
二:uploadAction
首先要继承execute方法
设置fileuploadinterceptor中的参数
表单属性:文件属性attach 还有text属性:info
其中类型 attachContentType(必须)
文件名称:attachFileName(必须)
设置完给他们一个set、get方法
最后把上次内容保存起来savePath(在xml中设置param)
保存语句FileUtils.copyFile(attach,new File(savePath+attachFileName));把attach中的文件拷贝到要保存的位置
此处使用注入
代码如下:
public class UploadAction extends ActionSupport {
/*
*
*/
//1.接收上次文件,名字来自于 表达的file的name属性名称
private File attach;
//2.接收文件类型
private String attachContentType;
//3.接收文件名称
private String attachFileName;
//4 接收描述
private String info;
//5.保存路径
private String savePath;
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public File getAttach() {
return attach;
}
public void setAttach(File attach) {
this.attach = attach;
}
public String getAttachContentType() {
return attachContentType;
}
public void setAttachContentType(String attachContentType) {
this.attachContentType = attachContentType;
}
public String getAttachFileName() {
return attachFileName;
}
public void setAttachFileName(String attachFileName) {
this.attachFileName = attachFileName;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String execute() throws Exception{
System.out.println(attach);
System.out.println(attachContentType);
System.out.println(attachFileName);
System.out.println(info);
/*
* 把文件保存到服务器硬盘
*/
FileUtils.copyFile(attach, new File(savePath+attachFileName));
return super.execute();
}
}
三:设置
在uploadaction中相同的包中设置struts-upload.xml
<package name="upload" extends="struts-default" namespace="/upload">
<!-- 配置 -->
<action name="upload" class="gz.itcast.h_upload_down.UploadAction" >
<param name="savePath">e:/images/</param>要保存注入的路径
<result>/index.jsp</result>
</action>
<struts>
最后在src目录下struts.xml设置包含进来
<include file="gz/itcast/h_upload_down/struts-upload.xml"></include>
</struts>
优化:
一:如何修改临时文件存放路径
在src目录constant
<struts>
<constant name="struts.multipart.saveDir" value="e:/temps/"></constant>
</struts>
然后在struts.xml中包含constant。
二:如何设置上传文件大小
在src目录constant中设置structs
<constant name="struts.multipart.maxSize" value="10000000"></constant>
其他常量<constant name="struts.action.extension" value="action,do,,"></constant> .action .do的都可以
<constant name="struts.i18n.encoding" value="utf-8"> </constant> 修改请求的编码