Struts文件上传

最近在网上看了几篇关于Struts处理文件上传的文章,并进行了整理。但对其中一些问题还是有些迷惑,以待日后解决!

       现把代码贴出来以供初学者研究:

 

UploadUitl.java

 

/**

 * 这是一个辅助类,辅助完成上传功能。

 * 可以选择将文件保存在数据库里或保存在文件系统上

 * 并对文件的类型和大小进行了限制

 */

package com.hywavesoft.struts.commons;

import java.io.*;

public class UploadUtil {

    private static final String DATABASE_DEST = "database";

    private static final String FILE_DEST = "file";

    private static final int MAX_SIZE = 1024 * 1024;

private static final String[] TYPES = { ".jpg", ".gif", ".zip", ".rar" };

 

    public static void saveFile(String fileName, byte[] fileData, int size,

            String dest) throws FileNotFoundException, IOException {

        if (!checkSize(size)) {

            throw new IOException(size + " is too large !");

        }

        if (!checkType(fileName)) {

            throw new IOException("Unvaildate type !");

        }

        if (dest.equals(DATABASE_DEST)) {

            saveToDb(fileName, fileData);

        }

        if (dest.equals(FILE_DEST)) {

            saveToFile(fileName, fileData);

        }

    }

 

    private static void saveToDb(String fileName, byte[] fileData) {

    }

 

    private static void saveToFile(String fileName, byte[] fileData)

            throws FileNotFoundException, IOException {

        OutputStream o = new FileOutputStream(fileName);

        o.write(fileData);

        o.close();

    }

 

    public static void delFile(String fileName, String dest)

            throws NullPointerException, SecurityException {

        if (dest.equals(DATABASE_DEST)) {

            delFromDb(fileName);

        }

        if (dest.equals(FILE_DEST)) {

            delFromFile(fileName);

        }

    }

 

    private static void delFromDb(String fileName) {

    }

 

    private static void delFromFile(String fileName)

            throws NullPointerException, SecurityException {

        File file = new File(fileName);

        if (file.exists())

            file.delete();

    }

 

    private static boolean checkSize(int size) {

        if (size > MAX_SIZE)

            return false;

        return true;

    }

 

    private static boolean checkType(String fileName) {

        for (int i = 0; i < TYPES.length; i++) {

            if (fileName.toLowerCase().endsWith(TYPES[i])) {

                return true;

            }

        }

        return false;

    }

 

}

 

UploadAction.java

 

/**

 * org.apache.struts.upload.FormFileStruts处理文件上传的核心组件,提供了获得

 * 上传文件元数据的方法。

 */

package com.hywavesoft.struts.upload;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

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.hywavesoft.struts.commons.UploadUtil;

 

public class UploadAction extends BaseAction {

    public ActionForward execute(

        ActionMapping mapping,

        ActionForm form,

        HttpServletRequest request,

        HttpServletResponse response) throws Exception {

        UploadForm uploadForm = (UploadForm) form;

       

        FormFile file = uploadForm.getTheFile();

    

        String contentType = file.getContentType();

        String fileName = file.getFileName();

        int fileSize = file.getFileSize();

        byte[] fileDate = file.getFileData();

          

        String command = request.getParameter("command");

       

        if (command.equals(SAVE)){

            UploadUtil.saveFile(getPath("fileUpload")+fileName

,fileDate,fileSize,FILE_DEST);

        }      

        if (command.equals(DELETE)){

            UploadUtil.delFile(fileName,FILE_DEST);

        }

        file.destroy();

        return mapping.findForward("success");

    }

}

 

BaseAction.java

 

package com.hywavesoft.struts.upload;

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;

 

public abstract class BaseAction extends Action {

    protected static final String SAVE = "save";

    protected static final String DELETE = "delete";

    protected static final String DATABASE_DEST = "database";

    protected static final String FILE_DEST = "file";

    public abstract ActionForward execute(

        ActionMapping mapping,

        ActionForm form,

        HttpServletRequest request,

        HttpServletResponse response) throws Exception;

 

    public String getPath(String filePath){

        String path = getServlet().getServletContext().getRealPath(filePath) + "\\";

        return path;

    }

}

 

UploadForm.java

 

package com.hywavesoft.struts.upload;

import org.apache.struts.action.ActionForm;

import org.apache.struts.upload.FormFile;

 

public class UploadForm extends ActionForm {

    private FormFile theFile;

    public FormFile getTheFile() {

        return theFile;

    }

    public void setTheFile(FormFile theFile) {

        this.theFile = theFile;

    }

}

 

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>

   <data-sources />

   <form-beans >

      <form-bean name="uploadForm" type="com.hywavesoft.struts.upload.UploadForm" />

 

   </form-beans>

 

   <global-exceptions />

   <global-forwards />

   <action-mappings >

      <action

         attribute="uploadForm"

         input="/upload/upload.jsp"

         name="uploadForm"

         path="/upload"

         scope="request"

         type="com.hywavesoft.struts.upload.UploadAction">

         <forward name="success" path="/upload/success.jsp" />

      </action>

 

   </action-mappings>

 

   <message-resources parameter="com.hywavesoft.struts.ApplicationResources" />

</struts-config>

 

Upload.jsp

 

<%@ page language="java"%>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>

<html>

    <head>

        <title>JSP for uploadForm form</title>

    </head>

    <body>

        <html:form action="/upload" method="post" enctype="multipart/form-data">

            theFile : <html:file property="theFile"/><html:errors property="theFile"/><br/>

            <html:submit/><html:cancel/>

            <html:hidden property="command" value="save"/>

        </html:form>

    </body>

</html>

 

Success.jsp

 

<%@ page language="java"%>

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>

<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>

<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html:html locale="true">

  <head>

    <html:base />

    <title>success.jsp</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">

  </head>

  <body>

    <h1>Upload File Successful !</h1><hr>

  </body>

</html:html>