List of usage examples for org.apache.commons.fileupload MultipartStream setHeaderEncoding
public void setHeaderEncoding(String encoding)
From source file:com.oneis.appserver.FileUploads.java
/** * Handle the incoming stream, processing files. *///from w w w . j a v a 2 s . c o m public void performUploads(HttpServletRequest request) throws IOException, UserReportableFileUploadException { instructionsRequired = false; // Need a parser for parameters ParameterParser paramParser = new ParameterParser(); paramParser.setLowerCaseNames(true); // Thread ID is used for temporary filenames long threadId = Thread.currentThread().getId(); int fileId = 0; InputStream requestBody = request.getInputStream(); MultipartStream multipart = new MultipartStream(requestBody, boundary); multipart.setHeaderEncoding("UTF-8"); boolean nextPart = multipart.skipPreamble(); while (nextPart) { String headerPart = multipart.readHeaders(); // Parse headers, splitting out the bits we're interested in String name = null; String filename = null; Map<String, String> itemHeaders = HeaderParser.parse(headerPart, true /* keys to lower case */); String mimeType = itemHeaders.get("content-type"); String disposition = itemHeaders.get("content-disposition"); if (disposition != null) { Map disp = paramParser.parse(disposition, PARAMPARSER_SEPERATORS); name = (String) disp.get("name"); filename = (String) disp.get("filename"); } // Set a default MIME type if none is given (Safari may omit it) if (mimeType == null) { mimeType = "application/octet-stream"; } // Remove the path prefix from IE (before the length check) if (filename != null) { int slash1 = filename.lastIndexOf('/'); int slash2 = filename.lastIndexOf('\\'); int slash = (slash1 > slash2) ? slash1 : slash2; if (slash != -1) { filename = filename.substring(slash + 1); } } boolean isFile = (filename != null && filename.length() > 0); if (isFile) { // File - did the app server give instructions about it? Upload upload = files.get(name); if (upload == null) { // Looks like a file, but the app server didn't say it should be. Give up. throw new UserReportableFileUploadException( "A file was uploaded, but it was not expected by the application. Field name: '" + name + "'"); } String dir = upload.getSaveDirectory(); if (dir == null) { // Ooops. throw new IOException("app server didn't specify dir"); } // Generate a temporary filename File outFile = null; do { outFile = new File(String.format("%1$s/u%2$d.%3$d", dir, threadId, fileId++)); } while (!outFile.createNewFile()); OutputStream outStream = new FileOutputStream(outFile); // Decorate with a digest? MessageDigest digest = null; if (upload.getDigestName() != null) { try { digest = MessageDigest.getInstance(upload.getDigestName()); } catch (java.security.NoSuchAlgorithmException e) { digest = null; } if (digest != null) { outStream = new DigestOutputStream(outStream, digest); } } // Decorate with a decompressor? String filterName = upload.getFilterName(); if (filterName != null && filterName.equals("inflate")) { outStream = new InflaterOutputStream(outStream); } multipart.readBodyData(outStream); outStream.close(); String digestAsString = null; if (digest != null) { String.format("%1$s_digest", name); digestAsString = StringUtils.bytesToHex(digest.digest()); } upload.setUploadDetails(outFile.getPath(), digestAsString, mimeType, filename, outFile.length()); } else { // Normal field - just absorb a few k max of it, turn it into a field ByteArrayOutputStream value = new ByteArrayOutputStream(); // TODO: Limit request size as a whole, not on a per-parameter basis. multipart.readBodyData(new LimitedFilterOutputStream(value, MAX_TEXT_PARAMETER_LENGTH)); params.put(name, value.toString("UTF-8")); } nextPart = multipart.readBoundary(); } }
From source file:net.unicon.warlock.portlet.RequestReader.java
private static Map readMultipartContent(ActionRequest req) throws WarlockException { // Assertions. if (req == null) { String msg = "Argument 'req' cannot be null."; throw new IllegalArgumentException(msg); }//w ww . j av a 2s . c o m Map rslt = new HashMap(); try { // Read the boundry marker. int index = req.getContentType().indexOf("boundary="); if (index < 0) { String msg = "Unable to locate multipart boundry."; throw new WarlockException(msg); } byte[] boundary = req.getContentType().substring(index + 9).getBytes(); // Read the InputStream. InputStream input = req.getPortletInputStream(); MultipartStream multi = new MultipartStream(input, boundary); multi.setHeaderEncoding(req.getCharacterEncoding()); // ...necessary? boolean hasMoreParts = multi.skipPreamble(); while (hasMoreParts) { Map headers = parseHeaders(multi.readHeaders()); String fieldName = getFieldName(headers); if (fieldName != null) { String subContentType = (String) headers.get("Content-type".toLowerCase()); if (subContentType != null && subContentType.startsWith("multipart/mixed")) { throw new UnsupportedOperationException("Multiple-file request fields not supported."); /* let's see if we need this... // Multiple files. byte[] subBoundary = subContentType.substring(subContentType.indexOf("boundary=") + 9).getBytes(); multi.setBoundary(subBoundary); boolean nextSubPart = multi.skipPreamble(); while (nextSubPart) { headers = parseHeaders(multi.readHeaders()); if (getFileName(headers) != null) { FileItem item = createItem(headers, false); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } rslt.add(item.getFieldName(), item.getInputStream()); } else { // Ignore anything but files inside // multipart/mixed. multi.discardBodyData(); } nextSubPart = multi.readBoundary(); } multi.setBoundary(boundary); */ } else { if (getFileName(headers) != null) { // A single file. FileItem item = fac.createItem(getFieldName(headers), (String) headers.get("Content-type".toLowerCase()), false, getFileName(headers)); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } String path = item.getName().replace('\\', '/'); String[] tokens = path.split("/"); FileUpload fu = new FileUpload(tokens[tokens.length - 1], item.getSize(), item.getInputStream(), item.getContentType()); rslt.put(item.getFieldName(), new FileUpload[] { fu }); } else { // A form field. FileItem item = fac.createItem(getFieldName(headers), (String) headers.get("Content-type".toLowerCase()), true, null); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } List newEntry = new ArrayList(); if (rslt.get(item.getFieldName()) != null) { String[] oldEntry = (String[]) rslt.get(item.getFieldName()); newEntry.addAll(Arrays.asList(oldEntry)); } newEntry.add(item.getString()); rslt.put(item.getFieldName(), newEntry.toArray(new String[0])); } } } else { // Skip this part. multi.discardBodyData(); } hasMoreParts = multi.readBoundary(); } } catch (Throwable t) { String msg = "Unable to process multipart form data."; throw new WarlockException(msg, t); } return rslt; }
From source file:org.sapia.soto.state.cocoon.util.CocoonFileUploadBase.java
/** * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867 </a> * compliant <code>multipart/form-data</code> stream. If files are stored on * disk, the path is given by <code>getRepository()</code>. * //from w w w . jav a 2s .com * @param req * The servlet request to be parsed. * * @return A list of <code>FileItem</code> instances parsed from the * request, in the order that they were transmitted. * * @exception FileUploadException * if there are problems reading/parsing the request or storing * files. */ public List /* FileItem */ parseRequest(HttpRequest req) throws FileUploadException { if (null == req) { throw new NullPointerException("req parameter"); } ArrayList items = new ArrayList(); String contentType = req.getHeader(CONTENT_TYPE); if ((null == contentType) || (!contentType.startsWith(MULTIPART))) { throw new InvalidContentTypeException("the request doesn't contain a " + MULTIPART_FORM_DATA + " or " + MULTIPART_MIXED + " stream, content type header is " + contentType); } int requestSize = req.getContentLength(); if (requestSize == -1) { throw new UnknownSizeException("the request was rejected because it's size is unknown"); } if ((sizeMax >= 0) && (requestSize > sizeMax)) { throw new SizeLimitExceededException( "the request was rejected because " + "it's size exceeds allowed range"); } try { int boundaryIndex = contentType.indexOf("boundary="); if (boundaryIndex < 0) { throw new FileUploadException( "the request was rejected because " + "no multipart boundary was found"); } byte[] boundary = contentType.substring(boundaryIndex + 9).getBytes(); InputStream input = req.getInputStream(); MultipartStream multi = new MultipartStream(input, boundary); multi.setHeaderEncoding(headerEncoding); boolean nextPart = multi.skipPreamble(); while (nextPart) { Map headers = parseHeaders(multi.readHeaders()); String fieldName = getFieldName(headers); if (fieldName != null) { String subContentType = getHeader(headers, CONTENT_TYPE); if ((subContentType != null) && subContentType.startsWith(MULTIPART_MIXED)) { // Multiple files. byte[] subBoundary = subContentType.substring(subContentType.indexOf("boundary=") + 9) .getBytes(); multi.setBoundary(subBoundary); boolean nextSubPart = multi.skipPreamble(); while (nextSubPart) { headers = parseHeaders(multi.readHeaders()); if (getFileName(headers) != null) { FileItem item = createItem(headers, false); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } items.add(item); } else { // Ignore anything but files inside // multipart/mixed. multi.discardBodyData(); } nextSubPart = multi.readBoundary(); } multi.setBoundary(boundary); } else { FileItem item = createItem(headers, getFileName(headers) == null); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } items.add(item); } } else { // Skip this part. multi.discardBodyData(); } nextPart = multi.readBoundary(); } } catch (IOException e) { throw new FileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage()); } return items; }