1创建文件file.jsp
<form action="uploadfile" enctype="multipart/form-data" method="post">
<input type="file" name="myfile"/>
<input type="submit" value="提交"/>
</form>
2创建action
public class MyFileUpload extends ActionSupport{
privateString myfileFileName;
privateFile myfile;
privateString myfileContentType;
publicString upload() throws IOException{
//得到上传文件保存的路径
StringsavePath=ServletActionContext.getServletContext().getRealPath("/upload");
//上传后保存的文件
File outFile=new File(savePath+"/"+myfileFileName);
//上传文件操作
FileUtils.copyFile(myfile, outFile);
return"success";
}
//省略get/set方法
}
说明:上面的FileUtils.copyFile(face, outfile); 方法,使用Common-io.jar文件中的一个工具类。如果不使用该方法,可以自己实现文件的读写:
FileOutputStream fos = new FileOutputStream("D:/struts/"+myfileFileName);
FileInputStream fis = newFileInputStream(myfile);
byte[] b = new byte[1024];
int len = 0;
while((len =fis.read(b))!=-1){
fos.write(b,0,len);
}
fos.close();
fis.close();
3配置struts.xml文件
<action name="*file" class="base.MyFileUpload" method="{1}">
<result>/success.jsp</result>
</action>