本文主要两种方式,一:通过 FileUtils.copyFile(file, savefile);方法复制;二:通过字节流方式复制
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- struts2 framework --> <filter> <filter-name>struts</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter> <filter-name>struts-cleanup</filter-name> <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class> </filter> <filter-mapping> <filter-name>struts</filter-name> <url-pattern>*.do</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> <filter-mapping> <filter-name>struts-cleanup</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <include file="struts-default.xml" /> <!--方法一 --> <package name="uploadFile" extends="struts-default"> <action name="upload" class="com.nn.upload.UploadAction" method="upload"> <result name="success">/success.jsp</result> <result name="input">/index.jsp</result> </action> </package> <!--方法二 --> <package name="uploadFile2" extends="struts-default"> <action name="upload2" class="com.nn.upload.UploadAction" method="uploadByStream"> <param name="allowTypes">.bmp,.png,.gif,.jpeg,.jpg</param> <param name="savePath">/upload</param> <!-- 保存的真实路径 --> <result name="success">/success.jsp</result> <result name="input">/index.jsp</result> </action> </package> </struts>
struts.properties
struts.multipart.parser=jakarta struts.multipart.saveDir=/temp struts.multipart.maxSize=2097152 struts.i18n.encoding=utf-8 struts.locale=zh_CN struts.action.extension=do struts.custom.i18n.resources=globalMsg
UploadAction.java 主要代码
public class UploadAction extends ActionSupport { private File file; private String fileName; private String fileType; // 第二种方法中接受依赖注入的属性 private String savePath; private String allowTypes; /** * 第一种方法,使用FileUtils从temp中复制到相关路径下面,结束后temp中的文件自动被清楚 * @return */ public String upload() { String realpath = ServletActionContext.getServletContext().getRealPath("/upload"); if (file != null) { String name = this.getFileName().substring(1); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); this.setFileName(df.format(new Date())+name); //文件名字+日期 File savefile = new File(new File(realpath), this.getFileName()); if (!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs(); try { FileUtils.copyFile(file, savefile); } catch (IOException e) { e.printStackTrace(); } ActionContext.getContext().put("message", "文件上传成功!"); } return "success"; } /** * 第二站方式,通过字节流来复制 * @return */ public String uploadByStream(){ // 判断是否允许上传 String filterResult = findFileType(this.getAllowTypes().split(",")); if (filterResult != null) { ActionContext.getContext().put("typeError","您要上传的文件类型不正确"); return filterResult; } // 以服务器的文件保存地址和原文件名建立上传文件输出流 FileOutputStream fos; FileInputStream fis; String realpath = ServletActionContext.getServletContext().getRealPath(this.getSavePath()); try { String name = this.getFileName().substring(1); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); this.setFileName(df.format(new Date())+name); //文件名字+日期 realpath = realpath +"\\"+this.getFileName(); fos = new FileOutputStream(realpath); fis = new FileInputStream(this.getFile()); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); fis.close(); return SUCCESS; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return INPUT; } public String findFileType(String[] types) { String fileType = this.getFileType(); for (String type : types) { if (type.equals(fileType)) { return null; } } return INPUT; } //省略get set 方法 }
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <script type="text/javascript"> function check(){ var file = document.getElementById("file"); if(file != null){ var fileType = file.value.substr(file.value.lastIndexOf(".")).toLowerCase(); //截取类型,如.jpg var fileName = file.value.substr(file.value.lastIndexOf("\\")); //截取文件名字,如:/01.png document.getElementById("fileName").value = fileName; document.getElementById("fileType").value = fileType; return true; } alert("请选择文件"); return false; } </script> </head> <body> <p>stuts 2 文件上传实例 </p> ${requestScope.typeError} <!-- 第一种方式上传链接: <form action="/upload.do" method="post" enctype="multipart/form-data" onsubmit="return check();"> --> <form action="/upload2.do" method="post" enctype="multipart/form-data" onsubmit="return check();"> 上传文件:<input type="file" name="file" /><input type="submit" value="上传"/> <input type="hidden" name="fileType" id="fileType"/> <input type="hidden" name="fileName" id="fileName"/> </form> </body> </html>
success.jsp
<body> ${requestScope.message}<br> 文件名称:<input type="text" value="<s:property value="fileName"/>"/><br> 文件为:<img src="${pageContext.request.contextPath}/<s:property value="‘upload/‘+fileName"/>"><br> <s:debug></s:debug> </body>
源码下载地址:http://download.csdn.net/detail/u011518709/7896593
时间: 2024-10-24 23:49:38