Search in sources :

Example 1 with FileUploadException

use of org.apache.tomcat.util.http.fileupload.FileUploadException in project tomcat by apache.

the class DiskFileItem method write.

/**
 * A convenience method to write an uploaded item to disk. The client code
 * is not concerned with whether or not the item is stored in memory, or on
 * disk in a temporary location. They just want to write the uploaded item
 * to a file.
 * <p>
 * This implementation first attempts to rename the uploaded item to the
 * specified destination file, if the item was originally written to disk.
 * Otherwise, the data will be copied to the specified file.
 * <p>
 * This method is only guaranteed to work <em>once</em>, the first time it
 * is invoked for a particular item. This is because, in the event that the
 * method renames a temporary file, that file will no longer be available
 * to copy or rename again at a later time.
 *
 * @param file The {@code File} into which the uploaded item should
 *             be stored.
 *
 * @throws Exception if an error occurs.
 */
@Override
public void write(final File file) throws Exception {
    if (isInMemory()) {
        try (OutputStream fout = Files.newOutputStream(file.toPath())) {
            fout.write(get());
        } catch (IOException e) {
            throw new IOException("Unexpected output data");
        }
    } else {
        final File outputFile = getStoreLocation();
        if (outputFile == null) {
            /*
                 * For whatever reason we cannot write the
                 * file to disk.
                 */
            throw new FileUploadException("Cannot write uploaded file to disk!");
        }
        // Save the length of the file
        size = outputFile.length();
        /*
             * The uploaded file is being stored on disk
             * in a temporary location so move it to the
             * desired file.
             */
        if (file.exists() && !file.delete()) {
            throw new FileUploadException("Cannot write uploaded file to disk!");
        }
        if (!outputFile.renameTo(file)) {
            BufferedInputStream in = null;
            BufferedOutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(outputFile));
                out = new BufferedOutputStream(new FileOutputStream(file));
                IOUtils.copy(in, out);
                out.close();
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }
        }
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) DeferredFileOutputStream(org.apache.tomcat.util.http.fileupload.DeferredFileOutputStream) FileOutputStream(java.io.FileOutputStream) DeferredFileOutputStream(org.apache.tomcat.util.http.fileupload.DeferredFileOutputStream) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) FileUploadException(org.apache.tomcat.util.http.fileupload.FileUploadException) FileInputStream(java.io.FileInputStream)

Example 2 with FileUploadException

use of org.apache.tomcat.util.http.fileupload.FileUploadException in project tomcat70 by apache.

the class Request method parseParts.

private void parseParts() {
    // Return immediately if the parts have already been parsed
    if (parts != null || partsParseException != null) {
        return;
    }
    MultipartConfigElement mce = getWrapper().getMultipartConfigElement();
    if (mce == null) {
        if (getContext().getAllowCasualMultipartParsing()) {
            mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize());
        } else {
            parts = Collections.emptyList();
            return;
        }
    }
    Parameters parameters = coyoteRequest.getParameters();
    parameters.setLimit(getConnector().getMaxParameterCount());
    boolean success = false;
    try {
        File location;
        String locationStr = mce.getLocation();
        if (locationStr == null || locationStr.length() == 0) {
            location = ((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR));
        } else {
            // If relative, it is relative to TEMPDIR
            location = new File(locationStr);
            if (!location.isAbsolute()) {
                location = new File((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR), locationStr).getAbsoluteFile();
            }
        }
        if (!location.isDirectory()) {
            parameters.setParseFailedReason(FailReason.MULTIPART_CONFIG_INVALID);
            partsParseException = new IOException(sm.getString("coyoteRequest.uploadLocationInvalid", location));
            return;
        }
        // Create a new file upload handler
        DiskFileItemFactory factory = new DiskFileItemFactory();
        try {
            factory.setRepository(location.getCanonicalFile());
        } catch (IOException ioe) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = ioe;
            return;
        }
        factory.setSizeThreshold(mce.getFileSizeThreshold());
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);
        upload.setFileSizeMax(mce.getMaxFileSize());
        upload.setSizeMax(mce.getMaxRequestSize());
        parts = new ArrayList<Part>();
        try {
            List<FileItem> items = upload.parseRequest(new ServletRequestContext(this));
            int maxPostSize = getConnector().getMaxPostSize();
            int postSize = 0;
            String enc = getCharacterEncoding();
            Charset charset = null;
            if (enc != null) {
                try {
                    charset = B2CConverter.getCharset(enc);
                } catch (UnsupportedEncodingException e) {
                // Ignore
                }
            }
            for (FileItem item : items) {
                ApplicationPart part = new ApplicationPart(item, location);
                parts.add(part);
                if (part.getSubmittedFileName() == null) {
                    String name = part.getName();
                    String value = null;
                    try {
                        String encoding = parameters.getEncoding();
                        if (encoding == null) {
                            if (enc == null) {
                                encoding = Parameters.DEFAULT_ENCODING;
                            } else {
                                encoding = enc;
                            }
                        }
                        value = part.getString(encoding);
                    } catch (UnsupportedEncodingException uee) {
                        try {
                            value = part.getString(Parameters.DEFAULT_ENCODING);
                        } catch (UnsupportedEncodingException e) {
                        // Should not be possible
                        }
                    }
                    if (maxPostSize >= 0) {
                        // accurate but close enough.
                        if (charset == null) {
                            // Name length
                            postSize += name.getBytes().length;
                        } else {
                            postSize += name.getBytes(charset).length;
                        }
                        if (value != null) {
                            // Equals sign
                            postSize++;
                            // Value length
                            postSize += part.getSize();
                        }
                        // Value separator
                        postSize++;
                        if (postSize > maxPostSize) {
                            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
                            throw new IllegalStateException(sm.getString("coyoteRequest.maxPostSizeExceeded"));
                        }
                    }
                    parameters.addParameter(name, value);
                }
            }
            success = true;
        } catch (InvalidContentTypeException e) {
            parameters.setParseFailedReason(FailReason.INVALID_CONTENT_TYPE);
            partsParseException = new ServletException(e);
        } catch (FileUploadBase.SizeException e) {
            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
            checkSwallowInput();
            partsParseException = new IllegalStateException(e);
        } catch (FileUploadException e) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = new IOException(e);
        } catch (IllegalStateException e) {
            // addParameters() will set parseFailedReason
            checkSwallowInput();
            partsParseException = e;
        }
    } finally {
        if (partsParseException != null || !success) {
            parameters.setParseFailedReason(FailReason.UNKNOWN);
        }
    }
}
Also used : Parameters(org.apache.tomcat.util.http.Parameters) InvalidContentTypeException(org.apache.tomcat.util.http.fileupload.FileUploadBase.InvalidContentTypeException) ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) FileItem(org.apache.tomcat.util.http.fileupload.FileItem) MultipartConfigElement(javax.servlet.MultipartConfigElement) ServletFileUpload(org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload) FileUploadBase(org.apache.tomcat.util.http.fileupload.FileUploadBase) Part(javax.servlet.http.Part) ApplicationPart(org.apache.catalina.core.ApplicationPart) ApplicationPart(org.apache.catalina.core.ApplicationPart) File(java.io.File) FileUploadException(org.apache.tomcat.util.http.fileupload.FileUploadException)

Example 3 with FileUploadException

use of org.apache.tomcat.util.http.fileupload.FileUploadException in project tomcat70 by apache.

the class DiskFileItem method write.

/**
 * A convenience method to write an uploaded item to disk. The client code
 * is not concerned with whether or not the item is stored in memory, or on
 * disk in a temporary location. They just want to write the uploaded item
 * to a file.
 * <p>
 * This implementation first attempts to rename the uploaded item to the
 * specified destination file, if the item was originally written to disk.
 * Otherwise, the data will be copied to the specified file.
 * <p>
 * This method is only guaranteed to work <em>once</em>, the first time it
 * is invoked for a particular item. This is because, in the event that the
 * method renames a temporary file, that file will no longer be available
 * to copy or rename again at a later time.
 *
 * @param file The <code>File</code> into which the uploaded item should
 *             be stored.
 *
 * @throws Exception if an error occurs.
 */
@Override
public void write(File file) throws Exception {
    if (isInMemory()) {
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(file);
            fout.write(get());
            fout.close();
        } finally {
            IOUtils.closeQuietly(fout);
        }
    } else {
        File outputFile = getStoreLocation();
        if (outputFile != null) {
            // Save the length of the file
            size = outputFile.length();
            /*
                 * The uploaded file is being stored on disk
                 * in a temporary location so move it to the
                 * desired file.
                 */
            if (!outputFile.renameTo(file)) {
                BufferedInputStream in = null;
                BufferedOutputStream out = null;
                try {
                    in = new BufferedInputStream(new FileInputStream(outputFile));
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    IOUtils.copy(in, out);
                    out.close();
                } finally {
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(out);
                }
            }
        } else {
            /*
                 * For whatever reason we cannot write the
                 * file to disk.
                 */
            throw new FileUploadException("Cannot write uploaded file to disk!");
        }
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) DeferredFileOutputStream(org.apache.tomcat.util.http.fileupload.DeferredFileOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) FileInputStream(java.io.FileInputStream) FileUploadException(org.apache.tomcat.util.http.fileupload.FileUploadException)

Example 4 with FileUploadException

use of org.apache.tomcat.util.http.fileupload.FileUploadException in project tomcat by apache.

the class FileItemIteratorImpl method init.

protected void init(final FileUploadBase fileUploadBase, @SuppressWarnings("unused") final RequestContext pRequestContext) throws FileUploadException, IOException {
    final String contentType = ctx.getContentType();
    if ((null == contentType) || (!contentType.toLowerCase(Locale.ENGLISH).startsWith(FileUploadBase.MULTIPART))) {
        throw new InvalidContentTypeException(String.format("the request doesn't contain a %s or %s stream, content type header is %s", FileUploadBase.MULTIPART_FORM_DATA, FileUploadBase.MULTIPART_MIXED, contentType));
    }
    final long requestSize = ((UploadContext) ctx).contentLength();
    // N.B. this is eventually closed in MultipartStream processing
    final InputStream input;
    if (sizeMax >= 0) {
        if (requestSize != -1 && requestSize > sizeMax) {
            throw new SizeLimitExceededException(String.format("the request was rejected because its size (%s) exceeds the configured maximum (%s)", Long.valueOf(requestSize), Long.valueOf(sizeMax)), requestSize, sizeMax);
        }
        // N.B. this is eventually closed in MultipartStream processing
        input = new LimitedInputStream(ctx.getInputStream(), sizeMax) {

            @Override
            protected void raiseError(final long pSizeMax, final long pCount) throws IOException {
                final FileUploadException ex = new SizeLimitExceededException(String.format("the request was rejected because its size (%s) exceeds the configured maximum (%s)", Long.valueOf(pCount), Long.valueOf(pSizeMax)), pCount, pSizeMax);
                throw new FileUploadIOException(ex);
            }
        };
    } else {
        input = ctx.getInputStream();
    }
    String charEncoding = fileUploadBase.getHeaderEncoding();
    if (charEncoding == null) {
        charEncoding = ctx.getCharacterEncoding();
    }
    multiPartBoundary = fileUploadBase.getBoundary(contentType);
    if (multiPartBoundary == null) {
        // avoid possible resource leak
        IOUtils.closeQuietly(input);
        throw new FileUploadException("the request was rejected because no multipart boundary was found");
    }
    progressNotifier = new MultipartStream.ProgressNotifier(fileUploadBase.getProgressListener(), requestSize);
    try {
        multiPartStream = new MultipartStream(input, multiPartBoundary, progressNotifier);
    } catch (final IllegalArgumentException iae) {
        // avoid possible resource leak
        IOUtils.closeQuietly(input);
        throw new InvalidContentTypeException(String.format("The boundary specified in the %s header is too long", FileUploadBase.CONTENT_TYPE), iae);
    }
    multiPartStream.setHeaderEncoding(charEncoding);
}
Also used : LimitedInputStream(org.apache.tomcat.util.http.fileupload.util.LimitedInputStream) InputStream(java.io.InputStream) LimitedInputStream(org.apache.tomcat.util.http.fileupload.util.LimitedInputStream) IOException(java.io.IOException) UploadContext(org.apache.tomcat.util.http.fileupload.UploadContext) MultipartStream(org.apache.tomcat.util.http.fileupload.MultipartStream) FileUploadException(org.apache.tomcat.util.http.fileupload.FileUploadException)

Aggregations

FileUploadException (org.apache.tomcat.util.http.fileupload.FileUploadException)4 File (java.io.File)3 IOException (java.io.IOException)3 BufferedInputStream (java.io.BufferedInputStream)2 BufferedOutputStream (java.io.BufferedOutputStream)2 FileInputStream (java.io.FileInputStream)2 FileOutputStream (java.io.FileOutputStream)2 DeferredFileOutputStream (org.apache.tomcat.util.http.fileupload.DeferredFileOutputStream)2 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 UncheckedIOException (java.io.UncheckedIOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Charset (java.nio.charset.Charset)1 MultipartConfigElement (javax.servlet.MultipartConfigElement)1 ServletException (javax.servlet.ServletException)1 Part (javax.servlet.http.Part)1 ApplicationPart (org.apache.catalina.core.ApplicationPart)1 Parameters (org.apache.tomcat.util.http.Parameters)1 FileItem (org.apache.tomcat.util.http.fileupload.FileItem)1 FileUploadBase (org.apache.tomcat.util.http.fileupload.FileUploadBase)1