struts1上传文件(commons-fileupload)

  1. jsp
    <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
    <%
    	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 'index.jsp' starting page</title>
    		<meta http-equiv="pragma" content="no-cache">
    		<meta http-equiv="cache-control" content="no-cache">
    		<meta http-equiv="expires" content="0">
    		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    		<meta http-equiv="description" content="This is my page">
    		<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
    	</head>
    
    	<body>
    		<form action="toUploadFile.do" method="post" enctype="multipart/form-data">
    			<input type="file" name="file">
    			<input type="submit" value="upload">
    		</form>
    		${fileName }
    	</body>
    </html>
    
     
  2. struts-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
    
    <struts-config>	
    	<action-mappings>
    		<action path="/toUploadFile"
            type="com.yqh.action.UploadAction"
            parameter="toUploadFile">
            	<forward name="uploadFile" path="/index.jsp"></forward>
            </action>
    	</action-mappings>
    </struts-config>
     
  3. UploadAction
    package com.yqh.action;
    
    import java.io.File;
    import java.util.Iterator;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.actions.MappingDispatchAction;
    
    /**
     *上传文件
     */
    public class UploadAction extends MappingDispatchAction {
    	
    	private Log logger = LogFactory.getLog(UploadAction.class);
    	
    	public ActionForward toUploadFile(ActionMapping mapping, ActionForm form,
    			HttpServletRequest request, HttpServletResponse response) {
    		try {
    			String fileName = uploadFile(request);
    			
    			if (fileName == null) {
    				return mapping.findForward("InvalidFile");
    			}
    			request.setAttribute("fileName", fileName);
    			logger.info(" 执行了上传文件操作");
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return mapping.findForward("uploadFile");
    	}
    
    	private String uploadFile(HttpServletRequest request) {
    		String fileName = "";
    		try {
    
    			DiskFileItemFactory fc = new DiskFileItemFactory();
    			// 设置文件的最大限度,如果超出这个限度,则将文件写入磁盘
    			fc.setSizeThreshold(4000);
    			// 文件超过最大限度时,写入磁盘的临时路径
    			fc.setRepository(new File("c:\\tmp"));
    
    			ServletFileUpload fu = new ServletFileUpload(fc);
    			// 设置最大文件尺寸,单位为字节,这里是4MB
    			fu.setSizeMax(10194304);
    			
    			// 得到所有的文件
    			List fileItems = fu.parseRequest(request);
    			Iterator i = fileItems.iterator();
    			// 依次处理每一个文件
    			while (i.hasNext()) {
    				FileItem fi = (FileItem) i.next();
    				//获得文件名,这个文件名包括路径
    				fileName = fi.getName();
    				//限制文件类型
    //				if (!fileName.endsWith(".xls"))
    //					return null;
    				//限制文件大小
    //				if (fi.getSize() > 10194304)
    //					throw new RuntimeException("File is too large!");
    				fileName = fileName.substring(fileName.lastIndexOf("\\") + 1,
    						fileName.length());
    				// 写入文件
    				fi.write(new File("d:/upload/" + fileName));
    				System.out.println(fileName + " upload success");
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return fileName;
    	}
    }
    
     4.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">
    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
          <param-name>config</param-name>
          <param-value>/WEB-INF/struts-config.xml</param-value>
        </init-param>
       </servlet>
    
    
    
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
      </servlet-mapping>
    
    	<welcome-file-list>
    		<welcome-file>index.jsp</welcome-file>
    	</welcome-file-list>
    </web-app>
    
     

 5.附件是所需要的jar包

你可能感兴趣的:(upload)