Struts1和Struts2的文件上传
1 Struts1文件上传
1.1 表单设计
<form action="upload" method="post" enctype="multipart/form-data"> 请选择要上传的文件: <input type="file" name="upload"> <input type="submit" value="上传文件"> </form>
1.2 在struts-config.xml进行如下配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans > <form-bean name="uploadForm" type="com.upload.form.UploadForm"/> </form-beans> <global-exceptions /> <global-forwards /> <action-mappings > <action path="/upload" name="uploadForm" type="com.upload.action.UploadAction" > <forward name="error" path="/error.jsp"/> </action> </action-mappings> <!-- 可以在此处设置上传文件的大小 <controller maxFileSize="10M"/> --> </struts-config>
1.3 创建UploadForm类收集表单数据
package com.upload.form; import org.apache.struts.action.ActionForm; import org.apache.struts.upload.FormFile; public class UploadForm extends ActionForm { private FormFile uploadFile; public FormFile getUploadFile() { return uploadFile; } public void setUploadFile(FormFile uploadFile) { this.uploadFile = uploadFile; } }
1.4 创建UploadAction类实现文件上传
package com.upload.action; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.upload.FormFile; import com.upload.form.UploadForm; public class UploadAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // 获取UploadForm实例 UploadForm uploadForm = (UploadForm) form; // 获取表单中上传的文件 FormFile uploadFile = uploadForm.getUploadFile(); // 若上传的文件不为空,且文件大小<80KB if (uploadFile != null && uploadFile.getFileSize() < 80 * 1024) { // 获取文件名 String fileName = uploadFile.getFileName(); // 编译一个文件后缀为jpg、png、gif的正则表达式 // \w+代表最少有一个任何一个字母或者数字或者下划线,最多不限制 Pattern pattern = Pattern .compile("^(?:\\w+\\.jpg|\\w+\\.png|\\w+\\.gif)$"); Matcher matcher = pattern.matcher(fileName); if (!matcher.matches()) { //在此返回错误提示页面 } // 创建新的文件名称 String newFileName = String.valueOf(System.currentTimeMillis()) + fileName.substring(fileName.lastIndexOf("\\") + 1); // 在服务器根目录下创建images文件夹 String realpath = request.getSession().getServletContext() .getRealPath("/images"); // 在该文件夹下创建上传文件的文件对象 File file = new File(realpath, newFileName); // 如果上传文件所在的文件夹不存在,则创建 if (!file.getParentFile().exists()) file.getParentFile().mkdir(); // 建立文件输出流 OutputStream outStream = new FileOutputStream(file); // 第一种上传方式 InputStream inStream = uploadFile.getInputStream(); byte[] data = new byte[1024]; int len = 0; while ((len = inStream.read(data)) != -1) { outStream.write(data, 0, len); } // 第二种上传方式 // outStream.write(uploadFile.getFileData()); // 上传结束 outStream.flush(); outStream.close(); } return null; } }
2 Struts2文件上传
2.1 设计表单
<form action="upload" method="post" enctype="multipart/form-data"> 请选择要上传的文件: <input type="file" name="upload"> <input type="submit" value="上传文件"> </form>
2.2 在struts.xml中进行配置
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 可以在此设置上传文件的大小,如超过这个大小,则抛出异常 <constant name="struts.multipart.maxSize" value="80 * 1000"/> --> <package name="upload" namespace="/" extends="struts-default"> <action name="upload" class="com.upload.action.UploadAction" method="uploadFile"> <result name="success">/index.jsp</result> </action> </package> </struts>
2.3 创建UploadAction类实现文件上传
package com.upload.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; public class UploadAction { // 得到上传的文件 private File upload; // 得到上传文件的文件类型 private String uploadContentType; // 得到上传文件的名称 private String uploadFileName; public void setUpload(File upload) { this.upload = upload; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } /** * 文件上传 * * @return */ public String uploadFile() { if (upload != null) { // 如果是图片文件 if ("image/pjpeg".equals(uploadContentType) || "image/gif".equals(uploadContentType)) { String newFileName = String.valueOf(System.currentTimeMillis()) + uploadFileName; // 在服务器根目录下创建images文件夹 String realpath = ServletActionContext.getServletContext() .getRealPath("/images"); // 在该文件夹下创建上传文件的文件对象 File destFile = new File(realpath, newFileName); System.out.println(destFile); // 如果上传文件所在的文件夹不存在,则创建 if (!destFile.getParentFile().exists()) destFile.getParentFile().mkdir(); try { // 利用基本方法上传文件 InputStream inStream = new FileInputStream(upload); OutputStream outStream = new FileOutputStream(destFile); byte[] data = new byte[1024]; int len = 0; while ((len = inStream.read(data)) != -1) { outStream.write(data, 0, len); } // 利用Struts2中的FileUtils工具类将上传的文件拷贝到目标文件中 // FileUtils.copyFile(upload, destFile); outStream.flush(); outStream.close(); inStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return "success"; } }
3 Struts2多文件上传
3.1 表单设计
<form action="upload" method="post" enctype="multipart/form-data"> 请选择要上传的文件:<br> <input type="file" name="upload"><br> <input type="file" name="upload"><br> <input type="file" name="upload"><br> <input type="submit" value="上传文件"> </form>
3.2 在struts.xml中进行配置
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 可以在此设置上传文件的大小,如超过这个大小,则抛出异常 <constant name="struts.multipart.maxSize" value="80 * 1000"/> --> <package name="upload" namespace="/" extends="struts-default"> <action name="upload" class="com.upload.action.UploadAction" method="uploadFile"> <result name="success">/index.jsp</result> </action> </package> </struts>
3.3 创建UploadAction实现多文件上传
package com.upload.action; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; public class UploadAction { // 得到上传的文件 private File[] upload; // 得到上传文件的文件类型 private String[] uploadContentType; // 得到上传文件的名称 private String[] uploadFileName; public void setUpload(File[] upload) { this.upload = upload; } public void setUploadContentType(String[] uploadContentType) { this.uploadContentType = uploadContentType; } public void setUploadFileName(String[] uploadFileName) { this.uploadFileName = uploadFileName; } /** * 文件上传 * * @return */ public String uploadFile() { if (upload != null) { String realpath = ServletActionContext.getServletContext() .getRealPath("/images"); File saveDir = new File(realpath); if (!saveDir.exists()) saveDir.mkdirs(); for (int i = 0; i < upload.length; i++) { if ("image/pjpeg".equals(uploadContentType[i]) || "image/gif".equals(uploadContentType[i])) { String newFileName = String.valueOf(System .currentTimeMillis()) + uploadFileName[i]; File destFile = new File(saveDir, newFileName); try { FileUtils.copyFile(upload[i], destFile); } catch (IOException e) { e.printStackTrace(); } } } } return "success"; } }
--------------------------------------------
补充:
BufferedReader reader = new BufferedReader(new InputStreamReader(uploadFile.getInputStream())); List list = new ArrayList(); reader.readLine();//跳过第一行 String strLine; while ((strLine = reader.readLine()) != null) { String[] str = strLine.split(","); if (str.length > 0) { list .add(str[0]); } }