Struts中FormFile用于文件进行上传
1.在jsp文件中进行定义
<form action="/StrutsFileUpAndDown/register.do" method="post" enctype="multipart/form-data"> ??名字:<input type="text" name="name" /> ??头像:<input type="file" name="file"/> ??<input type="submit" value="注册用户"> ??</form>
2.在Form表单中定义FormFile
/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */package com.yourcompany.struts.form;import javax.servlet.http.HttpServletRequest;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionMapping;import org.apache.struts.upload.FormFile;/** ?* MyEclipse Struts * Creation date: 08-24-2017 * ?* XDoclet definition: * @struts.form name="userForm" */public class UserForm extends ActionForm {/* * Generated Methods */private String username;private FormFile file;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public FormFile getFile() {return file;}public void setFile(FormFile file) {this.file = file;}}
3.利用struts文件进行关联Form,关联以后
1)利用表单实例进行获取FormFile实例,在获取以后,我们可以通过FormFile获取上传文件的各种信息
UserForm userForm = (UserForm) form;String username = userForm.getUsername();FormFile file = userForm.getFile();//通过formFile可以获取关于用户上传文件的各种信息//用于获取文件名字String fileName = file.getFileName();//用于获取文件大小int fileSize = file.getFileSize();
2)通过FormFile实例获取输入流,创建一个输出流,并且在代码中获取tomcat服务器的绝对路径
try {//获取输入流is = file.getInputStream();//得到输出流//1.得到file文件夹,上传到tomcat服务器后的绝对路径(file文件为新创建的文件夹) String filePath = this.getServlet().getServletContext().getRealPath("/file");//两个"//"的其中一个"/"为转义符 os=new FileOutputStream(filePath+"\\"+fileName); int len=0;//表示读取的字节//做一个缓存,防止文件过大而造成错误byte[] buff=new byte[1024];while((len=is.read(buff))!=-1){os.write(buff,0,len);}is.close();os.close(); }
Struts文件上传(FormFile)
原文地址:http://www.cnblogs.com/callyblog/p/7425138.html