struts实现文件的上传,有三个部分:JSP页面,Action,struts.xmlhtml
1.JSP页面java
<s:file name="image" label="请选择文件"></s:file> <s:submit value="上传"></s:submit>
2.Action中服务器
//用于保存页面file控件上传的数据 private File image; //保存上传文件的名称 //格式必须是:页面file控件的名称再加上FileName的格式 private String imageFileName; //保存上传文件的类型,如image、doc、zip等 //格式必须是:页面file控件的名称再加上FileContent的格式 private String imageContentType; public String execute() throws Exception { //获取文件上传后在服务器保存的位置 //注意要在Webcontent下建立 //images文件夹用于保存文件 String path= ServletActionContext.getServletContext() .getRealPath("/images"); //按照原文件名在images文件夹下构建文件 File file= new File(path+"//"+imageFileName); //利用commons-io包中的FileUtiles类实现文件上传 FileUtils.copyFile(image, file); return SUCCESS; }
3.struts配置jsp
<struts> <!-- 设置上传文件的临时目录 --> <constant name="struts.multipart.saveDir" value="e:\\temp"></constant> <!-- 设置上传文件的大小 --> <constant name="struts.multipart.maxSize" value="2097152"></constant> <package name="file" extends="struts-default" namespace="/"> <action name="fileAction" class="com.action.FileAction"> <result name="success">/success.jsp</result> </action> </package> </struts>
分析:
文件上传过程:在页面点击上传以后,会在临时目录上会生成临时文件(临时文件的路径在struts的配置文件中constant的struts.multipart.saveDir中设置,若是没有设置,就是默认的Javax.servlet.context.tempDir;)
在Action中接收的image文件就是这个临时文件。
在Action的execute方法中,路径path是文件上传到服务器上以后,该文件在服务器上的路径,
这里是经过ServletActionContext.getServletContext().getRealPath("/images")获取images文件夹在服务器上的绝对路径,
由于要把上传的文件放在images文件夹下,因此path+fileName,就是文件的绝对路径了;
而后使用new File(path+fileName)建立文件;
FileUtils.copyFile(image,file);把本地的临时文件上传到了服务器上。
spa