⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 extendedmultipartrequesthandler.java

📁 ajax-upload2 Sstruts文件上传
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package net.kencochrane.upload;

/*
 * $Id: CommonsMultipartRequestHandler.java 54929 2004-10-16 16:38:42Z germuska $
 *
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.Globals;
import org.apache.struts.upload.MultipartRequestHandler;
import org.apache.struts.upload.CommonsMultipartRequestHandler;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestWrapper;
import be.telio.mediastore.ui.upload.UploadListener;
import be.telio.mediastore.ui.upload.MonitoredDiskFileItemFactory;


 /**
  * This class implements the <code>MultipartRequestHandler</code> interface
  * by providing a wrapper around the Jakarta Commons FileUpload library.
  *
  * @version $Rev: 54929 $ $Date: 2004-10-16 17:38:42 +0100 (Sat, 16 Oct 2004) $
  * @since Struts 1.1
  */
public class ExtendedMultiPartRequestHandler implements MultipartRequestHandler {


    // ----------------------------------------------------- Manifest Constants


    /**
     * The default value for the maximum allowable size, in bytes, of an
     * uploaded file. The value is equivalent to 250MB.
     */
    public static final long DEFAULT_SIZE_MAX = 250 * 1024 * 1024;


    /**
     * The default value for the threshold which determines whether an uploaded
     * file will be written to disk or cached in memory. The value is equivalent
     * to 250KB.
     */
    public static final int DEFAULT_SIZE_THRESHOLD = 256 * 1024;


    // ----------------------------------------------------- Instance Variables


    /**
     * Commons Logging instance.
     */
    protected static Log log = LogFactory.getLog(
            CommonsMultipartRequestHandler.class);


    /**
     * The combined text and file request parameters.
     */
    private Hashtable elementsAll;


    /**
     * The file request parameters.
     */
    private Hashtable elementsFile;


    /**
     * The text request parameters.
     */
    private Hashtable elementsText;


    /**
     * The action mapping  with which this handler is associated.
     */
    private ActionMapping mapping;


    /**
     * The servlet with which this handler is associated.
     */
    private ActionServlet servlet;


    // ---------------------------------------- MultipartRequestHandler Methods


    /**
     * Retrieves the servlet with which this handler is associated.
     *
     * @return The associated servlet.
     */
    public ActionServlet getServlet() {
        return this.servlet;
    }


    /**
     * Sets the servlet with which this handler is associated.
     *
     * @param servlet The associated servlet.
     */
    public void setServlet(ActionServlet servlet) {
        this.servlet = servlet;
    }


    /**
     * Retrieves the action mapping with which this handler is associated.
     *
     * @return The associated action mapping.
     */
    public ActionMapping getMapping() {
        return this.mapping;
    }


    /**
     * Sets the action mapping with which this handler is associated.
     *
     * @param mapping The associated action mapping.
     */
    public void setMapping(ActionMapping mapping) {
        this.mapping = mapping;
    }

    /**
     * Parses the input stream and partitions the parsed items into a set of
     * form fields and a set of file items. In the process, the parsed items
     * are translated from Commons FileUpload <code>FileItem</code> instances
     * to Struts <code>FormFile</code> instances.
     *
     * @param request The multipart request to be processed.
     *
     * @throws ServletException if an unrecoverable error occurs.
     */
    public void handleRequest(HttpServletRequest request)
            throws ServletException {

        // Get the app config for the current request.
        ModuleConfig ac = (ModuleConfig) request.getAttribute(
                Globals.MODULE_KEY);

        //----------------------------------------------------------
        //  Changed this section of code, that is it.
        //-----------------------------------------------------------
        log.debug("Handling the request..");
        UploadListener listener = new UploadListener(request, 1);
        log.debug("uploading file with optional monitoring..");
        // Create a factory for disk-based file items
        FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
        log.debug("got the factory now get the ServletFileUpload");
        ServletFileUpload upload = new ServletFileUpload(factory);
        log.debug("Should have the ServletFileUpload by now.");
        // The following line is to support an "EncodingFilter"
        // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255
        upload.setHeaderEncoding(request.getCharacterEncoding());
        // Set the maximum size before a FileUploadException will be thrown.
        upload.setSizeMax(getSizeMax(ac));
       //----------------------------------------------------------------
        // Create the hash tables to be populated.
        elementsText = new Hashtable();
        elementsFile = new Hashtable();
        elementsAll = new Hashtable();

        // Parse the request into file items.
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (DiskFileUpload.SizeLimitExceededException e) {
            // Special handling for uploads that are too big.
            request.setAttribute(
                    MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED,
                    Boolean.TRUE);
            return;
        } catch (FileUploadException e) {
            log.error("Failed to parse multipart request", e);
            throw new ServletException(e);
        }

        // Partition the items into form fields and files.
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                addTextParameter(request, item);
            } else {
                addFileParameter(item);
            }
        }
    }


    /**
     * Returns a hash table containing the text (that is, non-file) request
     * parameters.
     *
     * @return The text request parameters.
     */
    public Hashtable getTextElements() {
        return this.elementsText;
    }


    /**
     * Returns a hash table containing the file (that is, non-text) request
     * parameters.
     *
     * @return The file request parameters.
     */
    public Hashtable getFileElements() {
        return this.elementsFile;
    }


    /**
     * Returns a hash table containing both text and file request parameters.
     *
     * @return The text and file request parameters.
     */
    public Hashtable getAllElements() {
        return this.elementsAll;
    }


    /**
     * Cleans up when a problem occurs during request processing.
     */
    public void rollback() {
        Iterator iter = elementsFile.values().iterator();

        while (iter.hasNext()) {
            FormFile formFile = (FormFile) iter.next();

            formFile.destroy();
        }
    }


    /**
     * Cleans up at the end of a request.
     */
    public void finish() {
        rollback();
    }


    // -------------------------------------------------------- Support Methods


    /**
     * Returns the maximum allowable size, in bytes, of an uploaded file. The
     * value is obtained from the current module's controller configuration.
     *
     * @param mc The current module's configuration.
     *
     * @return The maximum allowable file size, in bytes.
     */
    protected long getSizeMax(ModuleConfig mc) {
        return convertSizeToBytes(
                mc.getControllerConfig().getMaxFileSize(),
                DEFAULT_SIZE_MAX);
    }


    /**
     * Returns the size threshold which determines whether an uploaded file
     * will be written to disk or cached in memory.
     *
     * @param mc The current module's configuration.
     *
     * @return The size threshold, in bytes.
     */
    protected long getSizeThreshold(ModuleConfig mc) {
        return convertSizeToBytes(
                mc.getControllerConfig().getMemFileSize(),
                DEFAULT_SIZE_THRESHOLD);
    }

    /**
     * Converts a size value from a string representation to its numeric value.
     * The string must be of the form nnnm, where nnn is an arbitrary decimal
     * value, and m is a multiplier. The multiplier must be one of 'K', 'M' and
     * 'G', representing kilobytes, megabytes and gigabytes respectively.
     *
     * If the size value cannot be converted, for example due to invalid syntax,
     * the supplied default is returned instead.
     *
     * @param sizeString  The string representation of the size to be converted.
     * @param defaultSize The value to be returned if the string is invalid.
     *

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -