论坛首页 入门技术论坛

Struts文件上传方法

浏览 2318 次
该帖已经被评为新手帖
作者 正文
   发表时间:2008-12-21   最后修改:2008-12-21
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.FormFile是Struts处理文件上传的核心组件,提供了获得
* 上传文件元数据的方法。
*/
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>


论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics