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

📄 multipartrequest.java

📁 国外的一套开源CRM
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
        int intContentLength, InputStream in, String strSaveDirectory,
        String strFilePrefix, int intMaxReadBytes)
        throws IllegalArgumentException, IOException {
        // IF strSaveDirectory == NULL, then we should ignore any files uploaded.
        if (strSaveDirectory != null) {
            fileOutPutDirectory = new File(strSaveDirectory);

            if (!fileOutPutDirectory.exists()) {
                throw new IOException("Directory [" + strSaveDirectory +
                    "] is invalid.");
            } else if (!fileOutPutDirectory.canWrite()) {
                throw new IOException("Directory [" + strSaveDirectory +
                    "] is readonly.");
            }
        }

        //set the prefix to be prepended to the file
        filePrefix = strFilePrefix;

        // Now initialise the object, which will actually call the parse method to parse multipart stream.
        init(debug, strContentTypeText, intContentLength, in, intMaxReadBytes);
    }

    /**
            This method should be called on the MultipartRequest itself, not on any
            instances of MultipartRequest, because this sets up the encoding for all
            instances of multipartrequest.  You can set the encoding to null, in which
            case the default encoding will be applied.  The default encoding if this method
            is not called has been set to ISO-8859-1, which seems to offer the best hope
            of support for international characters, such as german "Umlaut" characters.

            <b>Warning:</b> In multithreaded environments it is the responsibility of the
            implementer to make sure that this method is not called while another instance
            is be constructed.  When an instance of MultipartRequest is constructed, it parses
            the input data, and uses the result of getEncoding() to convert between bytes and
            strings.  If setEncoding() is called by another thread, then subsequent string conversions
            in the private parse() method will utilise this new encoding, which will cause serious
            problems.
    */
    public static synchronized void setEncoding(String enc)
        throws UnsupportedEncodingException {
        if ((enc == null) || (enc.trim() == "")) {
            charEncoding = System.getProperty("file.encoding");
        } else {
            // This will test the encoding for validity.
            new String(new byte[] { (byte) '\n' }, enc);

            charEncoding = enc;
        }
    }

    /**
            Returns the current encoding method.
    */
    public static String getEncoding() {
        return charEncoding;
    }

    /**
     * Initialise the parser.
     *
     * @param debug                                        A PrintWriter that can be used for debugging.
     * @param strContentTypeText         The &quot;Content-Type&quot; HTTP header value.
     * @param intContentLength                 The &quot;Content-Length&quot; HTTP header value.
     * @param in                                        The InputStream to read and parse.
     * @param strSaveDirectory                The temporary directory to save the file from where they can then be moved to wherever by the
     *                                                                 calling process.  <b>If you specify <u>null</u> for this parameter, then any files uploaded
     *                                                                will be silently ignored.</B>
     * @param intMaxReadBytes                Overrides the MAX_BYTES_READ value, to allow arbitrarily long files.
     *
     * @exception IllegalArgumentException         If the strContentTypeText does not contain a Content-Type of "multipart/form-data" or the boundary is not found.
     * @exception IOException                                If the intContentLength is higher than MAX_READ_BYTES or strSaveDirectory is invalid or cannot be written to.
     *
     * @see #MAX_READ_BYTES
     */
    private void init(PrintWriter debug, String strContentTypeText,
        int intContentLength, InputStream in, int intMaxReadBytes)
        throws IllegalArgumentException, IOException {
        // save reference to debug stream for later.
        this.debug = debug;

        if ((strContentTypeText != null) &&
                strContentTypeText.startsWith("multipart/form-data") &&
                (strContentTypeText.indexOf("boundary=") != -1)) {
            strBoundary = strContentTypeText.substring(strContentTypeText.indexOf(
                        "boundary=") + "boundary=".length()).trim();
        } else {
            // <mtl,jpell>
            debug("ContentType = " + strContentTypeText);
            throw new IllegalArgumentException("Invalid Content Type.");
        }

        this.intContentLength = intContentLength;

        // FIX: 1.15
        if (intContentLength > intMaxReadBytes) {
            debug("ContentLength = " + intContentLength);
            debug("MaxReadBytes = " + intMaxReadBytes);

            throw new IOException("Content Length Error (" + intContentLength +
                " > " + intMaxReadBytes + ")");
        }

        // Instantiate the hashtable...
        htParameters = new Hashtable();
        htFiles = new Hashtable();
        blockOfBytes = new byte[READ_LINE_BLOCK];

        // Even though this method would never normally be called more than once
        // in the objects lifetime, we will initialise it here anyway.
        intTotalRead = 0; // <David Tuma> - fix: 1.20

        // Now parse the data.
        parse(new BufferedInputStream(in));

        // No need for this once parse is complete.
        this.blockOfBytes = null;
        this.debug = null;
        this.strBoundary = null;
    }

    /**
            Return the value of the strName URLParameter.
          If more than one value for a particular Parameter, will return the first.
            If an error occurs will return null.
    */
    public String getURLParameter(String strName) {
        Object value = htParameters.get(strName);

        if (value instanceof Vector) {
            return (String) ((Vector) value).firstElement();
        } else {
            return (String) htParameters.get(strName);
        }
    }

    /**
            Return an enumeration of all values for the strName parameter.
            Even if a single value for, will always return an enumeration, although
            it may actually be empty if not value was encountered for strName or
            it is an invalid parameter name.
    */
    public Enumeration getURLParameters(String strName) {
        Object value = htParameters.get(strName);

        if (value instanceof Vector) {
            return ((Vector) value).elements();
        } else {
            Vector vector = new Vector();

            if (value != null) {
                vector.addElement(value);
            }

            return vector.elements();
        }
    }

    /**
            An enumeration of all URL Parameters for the current HTTP Request.
    */
    public Enumeration getParameterNames() {
        return htParameters.keys();
    }

    /**
            This enumeration will return all INPUT TYPE=FILE parameter NAMES as encountered
            during the upload.
    */
    public Enumeration getFileParameterNames() {
        return htFiles.keys();
    }

    /**
            Returns the Content-Type of a file.

            @see #getFileParameter(java.lang.String, int)
    */
    public String getContentType(String strName) {
        // Can cast null, it will be ignored.
        return (String) getFileParameter(strName, CONTENT_TYPE);
    }

    /**
            If files were uploaded into memory, this method will retrieve the contents
            of the file as a InputStream.

            @return the contents of the file as a InputStream, or null if not file uploaded,
            or file uploaded to file system directory.

            @see #getFileParameter(java.lang.String, int)
    */
    public InputStream getFileContents(String strName) {
        Object obj = getFileParameter(strName, CONTENTS);

        if (obj != null) {
            return new ByteArrayInputStream((byte[]) obj);
        } else {
            return null;
        }
    }

    /**
            Returns a File reference to the uploaded file.  This reference is to the files uploaded location,
            and allows you to read/move/delete the file.

            This method is only of use, if files were uploaded to the file system.  Will return null if
            uploaded to memory, in which case you should use getFileContents(strName) instead.

            @return Returns a null file reference if a call to getFileSize(strName) returns zero or files were
            uploaded to memory.

            @see #getFileSize(java.lang.String)
            @see #getFileContents(java.lang.String)
            @see #getFileSystemName(java.lang.String)
    */
    public File getFile(String strName) {
        String filename = getFileSystemName(strName);

        // Fix: If fileOutPutDirectory is null, then we are ignoring any file contents, so we must return null.
        if ((filename != null) && (getFileSize(strName) > 0) &&
                (fileOutPutDirectory != null)) {
            return new File(fileOutPutDirectory, filename);
        } else {
            return null;
        }
    }

    /**
            Get the file system basename of an uploaded file.

            @return null if strName not found.

            @see #getFileParameter(java.lang.String, int)
    */
    public String getFileSystemName(String strName) {
        // Can cast null, it will be ignored.
        return (String) getFileParameter(strName, FILENAME);
    }

    /**
            Returns the File Size of a uploaded file.

            @return -1 if file size not defined.

            @see #getFileParameter(java.lang.String, int)
    */
    public long getFileSize(String strName) {
        Object obj = getFileParameter(strName, SIZE);

        if (obj != null) {
            return ((Long) obj).longValue();
        } else {
            return (long) -1;
        }
    }

    /**
            Access an attribute of a file upload parameter record.

            @param strName is the form field name, used to upload the file.  This identifies
                            the formfield location in the storage facility.

            @param strFilename        This is the FileSystemName of the file
            @param type        What attribute you want from the File Parameter.
                    The following types are supported:
                            MultipartRequest.FILENAME,
                            MultipartRequest.CONTENT_TYPE,
                            MultipartRequest.SIZE,
                            MultipartRequest.CONTENTS

            The getFileSystemName(),getFileSize(),getContentType(),getContents() methods
            all use this method passing in a different type argument.

            <p><b>Note: </b>This class has been changed to provide for future functionality where you
            will be able to access all files uploaded, even if they are uploaded using the same
            form field name.  At this point however, only the first file uploaded via a form
            field name is accessible.</p>

            @see #getContentType(java.lang.String)
            @see #getFileSize(java.lang.String)
            @see #getFileContents(java.lang.String)
            @see #getFileSystemName(java.lang.String)
    */
    public Object getFileParameter(String strName, int type) {
        Object[] objArray = null;
        Object value = htFiles.get(strName);

        if (value instanceof Vector) {
            objArray = (Object[]) ((Vector) value).firstElement();
        } else {
            objArray = (Object[]) htFiles.get(strName);
        }

        // Now ensure valid value.
        if ((objArray != null) && (type >= FILENAME) && (type <= CONTENTS)) {
            return objArray[type];
        } else {
            return null;
        }
    }

    /**
            This is the main parse method.
    */
    private void parse(InputStream in) throws IOException {
        String strContentType = null;
        String strName = null;
        String strFilename = null;
        String strLine = null;
        int read = -1;

        // First run through, check that the first line is a boundary, otherwise throw a exception as format incorrect.

⌨️ 快捷键说明

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