Strut2学习笔记(2) - 简单的文件上传系统
简单的文件上传系统
1.编写FileAdd.jsp -(View)
<%@ page language="JAVA" contentType="TEXT/HTML; charset=UTF-8" pageEncoding="UTF-8" %><%@ taglib prefix="s" uri="/struts-tags" %>...<body> <h4>Add File<h4> <! enctype必须为multipart/form-data,该属性告诉框架这个请求需要被当做上传处理 > <s:form action="FileUploader" method="post" enctype="multipart/form-data" > <s:file name="file" label="FileName" /> <s:submit /> </s:form></body>...
public class FileUploader {//上传文件方法 public void FileUpload(File file, String fileName, String DestinationPath) { FileInputStream in; FileOutputStream out; File dir = new File(DestinationPath); //将给定路径名字符串转换为抽象路径名来创建一个新 File 实例,此File表示路径 if (!dir.exists()) { dir.mkdir(); //按DestinationPath创建一个文件夹 } //创建一个绝对路径targetPath String targetPath = dir.getPath() + dir.separator + fileName; File targetFile = new File(targetPath); //上传文件 try { in = new FileInputStream(file); out = new FileOutputStream(targetFile); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }}
public class FileUploaderAction extends ActionSupport { public String excute() { private fu = new FileUploader(); try { fu.FileUpload(getFile(), getFileName(), destinationPath); } catch (Exception ex) { ex.printStack(); } return SUCCESS; } private File file; private String fileName; private String destinationPath; ... /* 各成员变量的getter及setter */ }
<struts> <constant name="struts.devMode" value="true" /> <package name="Upload" extends="struts-default" > <action name="FileAdd" > <result>/FileAdd.jsp</result> </action> <action name="FileUploader" > <param name="destinationPath">./UploadFolder/</param> <result>/FileAdded.jsp</result> <result name="INPUT">/FileAdd.jsp</result> </action> </package></struts>
<meta http-equiv="REFRESH" content="1;URL=FileAdd.action" />