1 Action中的代码:
public class UploadFileAction extends ActionSupport { private List file; private String[] fileContentType; private String[] fileFileName; public List getFile() { return file; } public void setFile(List file) { this.file = file; } public String[] getFileContentType() { return fileContentType; } public void setFileContentType(String[] fileContentType) { this.fileContentType = fileContentType; } public String[] getFileFileName() { return fileFileName; } public void setFileFileName(String[] fileFileName) { this.fileFileName = fileFileName; } public String excute() { // 拿到上下文路径 String path = ServletActionContext.getServletContext().getRealPath( "/file"); if (file != null) { File filetemp = new File(path); if (!filetemp.exists()) { // 建立文件夹 filetemp.mkdir(); } try { for (int i = 0; i < file.size(); i++) { File f = new File(filetemp, fileFileName[i]); System.out.println("上传的文件为:" + fileFileName[i] + this.fileContentType[i]); FileUtils.copyFile(file.get(i), f); } } catch (IOException e) { e.printStackTrace(); } } System.out.println("上传成功"); return SUCCESS; } }
2.struts.xml中的配置
<package name="upload" namespace="/" extends="struts-default"> <action name="uploadAction" class="xxxxx.uploadAction"> <result name="success">/index.jsp</result> </action> </package>
3.JSP页面显示
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'upload.jsp' starting page</title> </head> <body> <s:form action="uploadAction!excute.action" enctype="multipart/form-data" method="post"> <s:file name="file"></s:file> <s:file name="file"></s:file> <s:file name="file"></s:file> <s:submit label="上传"></s:submit> </s:form> </body> </html>