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);
}
}
}
}
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);
}
}
}
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!");
}
}
}
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);
}
Aggregations