List of usage examples for org.apache.commons.fileupload MultipartStream readHeaders
public String readHeaders() throws MalformedStreamException
Reads the header-part
of the current encapsulation
.
From source file:com.rhfung.P2PDictionary.DataConnection.java
private void HandleReadPost(String contentLocation, String contentType, String accepts, ListInt senders, byte[] payload) { if (contentLocation.equals(ADDENTRY_NS_API) || contentLocation.equals(ADDENTRY_NS_BYTES_API) || contentLocation.equals(ADDENTRY_NS_MIME_API)) { boolean sendMime = contentLocation.equals(ADDENTRY_NS_MIME_API); String boundary = getBoundaryFromContentType(contentType); if (boundary == null) { WriteDebug("Cannot identify boundary from POST"); return; }// ww w .j a v a 2s . com String filename = "content"; try { MultipartStream multipartStream = new MultipartStream(new ByteArrayInputStream(payload), boundary.getBytes()); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { String header = multipartStream.readHeaders(); Hashtable<String, String> hdr = ReadHeaders( new InputStreamReader(new ByteArrayInputStream(header.getBytes()))); String val = hdr.get("Content-Disposition"); if (val != null) { final String FILENAME = "filename=\""; int filenameIdx = val.indexOf(FILENAME); filename = val.substring(filenameIdx + FILENAME.length(), val.indexOf("\"", filenameIdx + FILENAME.length())); } // process headers // create some output stream ByteArrayOutputStream output = new ByteArrayOutputStream(); multipartStream.readBodyData(output); if (sendMime) { String valType = hdr.get("Content-Type"); controller.put(filename, new MIMEByteObject(valType, output.toByteArray())); } else { controller.put(filename, output.toByteArray()); } nextPart = multipartStream.readBoundary(); } // only reply back with ONE file uploaded MemoryStream bufferedOutput = new MemoryStream(); String key = controller.getFullKey(filename); dataLock.readLock().lock(); try { DataEntry entry = data.get(key); WriteResponseInfo(bufferedOutput.createStreamWriter(), ADDENTRY_NS_API, entry); synchronized (sendBuffer) { sendBuffer.add(bufferedOutput); } } finally { dataLock.readLock().unlock(); } } catch (Exception e) { MemoryStream bufferedOutput = new MemoryStream(); WriteErrorNotFound(bufferedOutput.createStreamWriter(), "GET", contentLocation, 500); synchronized (sendBuffer) { sendBuffer.add(bufferedOutput); } } } else { MemoryStream bufferedOutput = new MemoryStream(); WriteErrorNotFound(bufferedOutput.createStreamWriter(), "GET", contentLocation, 501); synchronized (sendBuffer) { sendBuffer.add(bufferedOutput); } } }
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); }/*from w ww . j a v a 2 s . co 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.eclipse.che.api.builder.internal.SourcesManagerImpl.java
private void download(String downloadUrl, java.io.File downloadTo) throws IOException { HttpURLConnection conn = null; try {/*from w ww . j ava 2 s . c o m*/ final LinkedList<java.io.File> q = new LinkedList<>(); q.add(downloadTo); final long start = System.currentTimeMillis(); final List<Pair<String, String>> md5sums = new LinkedList<>(); while (!q.isEmpty()) { java.io.File current = q.pop(); java.io.File[] list = current.listFiles(); if (list != null) { for (java.io.File f : list) { if (f.isDirectory()) { q.push(f); } else { md5sums.add(Pair.of(com.google.common.io.Files.hash(f, Hashing.md5()).toString(), downloadTo.toPath().relativize(f.toPath()).toString().replace("\\", "/"))); //Replacing of "\" is need for windows support } } } } final long end = System.currentTimeMillis(); if (md5sums.size() > 0) { LOG.debug("count md5sums of {} files, time: {}ms", md5sums.size(), (end - start)); } conn = (HttpURLConnection) new URL(downloadUrl).openConnection(); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); final EnvironmentContext context = EnvironmentContext.getCurrent(); if (context.getUser() != null && context.getUser().getToken() != null) { conn.setRequestProperty(HttpHeaders.AUTHORIZATION, context.getUser().getToken()); } if (!md5sums.isEmpty()) { conn.setRequestMethod(HttpMethod.POST); conn.setRequestProperty("Content-type", MediaType.TEXT_PLAIN); conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.MULTIPART_FORM_DATA); conn.setDoOutput(true); try (OutputStream output = conn.getOutputStream(); Writer writer = new OutputStreamWriter(output)) { for (Pair<String, String> pair : md5sums) { writer.write(pair.first); writer.write(' '); writer.write(pair.second); writer.write('\n'); } } } final int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { final String contentType = conn.getHeaderField("content-type"); if (contentType.startsWith(MediaType.MULTIPART_FORM_DATA)) { final HeaderParameterParser headerParameterParser = new HeaderParameterParser(); final String boundary = headerParameterParser.parse(contentType).get("boundary"); try (InputStream in = conn.getInputStream()) { MultipartStream multipart = new MultipartStream(in, boundary.getBytes()); boolean hasMore = multipart.skipPreamble(); while (hasMore) { final Map<String, List<String>> headers = parseChunkHeader( CharStreams.readLines(new StringReader(multipart.readHeaders()))); final List<String> contentDisposition = headers.get("content-disposition"); final String name = headerParameterParser.parse(contentDisposition.get(0)).get("name"); if ("updates".equals(name)) { int length = -1; List<String> contentLengthHeader = headers.get("content-length"); if (contentLengthHeader != null && !contentLengthHeader.isEmpty()) { length = Integer.parseInt(contentLengthHeader.get(0)); } if (length < 0 || length > 204800) { java.io.File tmp = java.io.File.createTempFile("tmp", ".zip", directory); try { try (FileOutputStream fOut = new FileOutputStream(tmp)) { multipart.readBodyData(fOut); } ZipUtils.unzip(tmp, downloadTo); } finally { if (tmp.exists()) { tmp.delete(); } } } else { final ByteArrayOutputStream bOut = new ByteArrayOutputStream(length); multipart.readBodyData(bOut); ZipUtils.unzip(new ByteArrayInputStream(bOut.toByteArray()), downloadTo); } } else if ("removed-paths".equals(name)) { final ByteArrayOutputStream bOut = new ByteArrayOutputStream(); multipart.readBodyData(bOut); final String[] removed = JsonHelper.fromJson( new ByteArrayInputStream(bOut.toByteArray()), String[].class, null); for (String path : removed) { java.io.File f = new java.io.File(downloadTo, path); if (!f.delete()) { throw new IOException(String.format("Unable delete %s", path)); } } } else { // To /dev/null :) multipart.readBodyData(DEV_NULL); } hasMore = multipart.readBoundary(); } } } else { try (InputStream in = conn.getInputStream()) { ZipUtils.unzip(in, downloadTo); } } } else if (responseCode != HttpURLConnection.HTTP_NO_CONTENT) { throw new IOException( String.format("Invalid response status %d from remote server. ", responseCode)); } } catch (ParseException | JsonParseException e) { throw new IOException(e.getMessage(), e); } finally { if (conn != null) { conn.disconnect(); } } }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
private void handlePostBlob(HttpServletRequest request, HttpServletResponse response, InputStream is, BlobStore blobStore, String containerName) throws IOException, S3Exception { String boundaryHeader = request.getHeader(HttpHeaders.CONTENT_TYPE); if (boundaryHeader == null || !boundaryHeader.startsWith("multipart/form-data; boundary=")) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return;/*w w w . ja v a 2 s. c o m*/ } String boundary = boundaryHeader.substring(boundaryHeader.indexOf('=') + 1); String blobName = null; String contentType = null; String identity = null; // TODO: handle policy byte[] policy = null; String signature = null; byte[] payload = null; MultipartStream multipartStream = new MultipartStream(is, boundary.getBytes(StandardCharsets.UTF_8), 4096, null); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { String header = multipartStream.readHeaders(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { multipartStream.readBodyData(baos); if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"acl\"")) { // TODO: acl } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"AWSAccessKeyId\"")) { identity = new String(baos.toByteArray()); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"Content-Type\"")) { contentType = new String(baos.toByteArray()); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"file\"")) { // TODO: buffers entire payload payload = baos.toByteArray(); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"key\"")) { blobName = new String(baos.toByteArray()); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"policy\"")) { policy = baos.toByteArray(); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"signature\"")) { signature = new String(baos.toByteArray()); } } nextPart = multipartStream.readBoundary(); } if (identity == null || signature == null || blobName == null || policy == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } Map.Entry<String, BlobStore> provider = blobStoreLocator.locateBlobStore(identity, null, null); if (provider == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } String credential = provider.getKey(); Mac mac; try { mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1")); } catch (InvalidKeyException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } String expectedSignature = BaseEncoding.base64().encode(mac.doFinal(policy)); if (!signature.equals(expectedSignature)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } BlobBuilder.PayloadBlobBuilder builder = blobStore.blobBuilder(blobName).payload(payload); if (contentType != null) { builder.contentType(contentType); } Blob blob = builder.build(); blobStore.putBlob(containerName, blob); response.setStatus(HttpServletResponse.SC_NO_CONTENT); }
From source file:org.jwifisd.eyefi.Main3.java
public static void main(String[] args) throws Exception { MultipartStream stream = new MultipartStream( new FileInputStream("src/main/resources/NanoHTTPD-977513220698581430"), "---------------------------02468ace13579bdfcafebabef00d".getBytes()); ByteArrayOutputStream output = new ByteArrayOutputStream(); String readHeaders = stream.readHeaders(); System.out.println(readHeaders.toString()); stream.readBodyData(output);//from w w w . j ava 2 s .co m output = new ByteArrayOutputStream(); readHeaders = stream.readHeaders(); System.out.println(readHeaders.toString()); stream.readBodyData(output); final InputStream in = new FileInputStream("src/main/resources/NanoHTTPD-977513220698581430"); FileItemIterator iter = new FileUpload().getItemIterator(new RequestContext() { @Override public InputStream getInputStream() throws IOException { return in; } @Override public String getContentType() { // TODO Auto-generated method stub return "multipart/form-data; boundary=---------------------------02468ace13579bdfcafebabef00d"; } @Override public int getContentLength() { return 4237763; } @Override public String getCharacterEncoding() { // TODO Auto-generated method stub return "UTF-8"; } }); while (iter.hasNext()) { FileItemStream item = iter.next(); System.out.println("name:" + item.getName()); System.out.println("name:" + item.getContentType()); //item.openStream(); } }
From source file:org.kuali.test.proxyserver.MultiPartHandler.java
public MultiPartHandler(MultipartStream multipartStream) throws IOException { LineNumberReader lnr = null;//from w w w .j av a 2 s . co m try { lnr = new LineNumberReader(new StringReader(multipartStream.readHeaders())); String line; while ((line = lnr.readLine()) != null) { if (line.startsWith(Constants.CONTENT_DISPOSITION)) { for (String param : PARAMETER_NAMES) { int pos = line.indexOf(param); if (pos > -1) { pos += (param.length() + 2); int pos2 = line.indexOf("\"", pos); if ((pos > -1) && (pos2 > -1) && (pos2 > pos)) { parameters.put(param, line.substring(pos, pos2)); } } } } if (line.startsWith(Constants.HTTP_RESPONSE_CONTENT_TYPE)) { int pos = line.indexOf(Constants.SEPARATOR_COLON); if (pos > -1) { contentType = line.substring(pos + 1).trim(); } } } ByteArrayOutputStream bos = new ByteArrayOutputStream(512); multipartStream.readBodyData(bos); bytes = bos.toByteArray(); } finally { try { if (lnr != null) { lnr.close(); } } catch (Exception ex) { } ; } }
From source file:org.opendatakit.services.sync.service.logic.AggregateSynchronizer.java
@Override public void downloadInstanceFileBatch(List<CommonFileAttachmentTerms> filesToDownload, String serverInstanceFileUri, String instanceId, String tableId) throws HttpClientWebException, IOException { // boolean downloadedAllFiles = true; URI instanceFilesDownloadUri = wrapper.constructInstanceFileBulkDownloadUri(serverInstanceFileUri, instanceId);//w ww. j a v a 2s.co m ArrayList<OdkTablesFileManifestEntry> entries = new ArrayList<OdkTablesFileManifestEntry>(); for (CommonFileAttachmentTerms cat : filesToDownload) { OdkTablesFileManifestEntry entry = new OdkTablesFileManifestEntry(); entry.filename = cat.rowPathUri; entries.add(entry); } OdkTablesFileManifest manifest = new OdkTablesFileManifest(); manifest.setFiles(entries); String boundaryVal = null; InputStream inStream = null; OutputStream os = null; HttpPost request = new HttpPost(); CloseableHttpResponse response = null; // no body content-type and no response content-type requested wrapper.buildBasicRequest(instanceFilesDownloadUri, request); request.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType()); String fileManifestEntries = ODKFileUtils.mapper.writeValueAsString(manifest); HttpEntity entity = new StringEntity(fileManifestEntries, Charset.forName("UTF-8")); request.setEntity(entity); try { response = wrapper.httpClientExecute(request, HttpRestProtocolWrapper.SC_OK_ONLY); Header hdr = response.getEntity().getContentType(); hdr.getElements(); HeaderElement[] hdrElem = hdr.getElements(); for (HeaderElement elm : hdrElem) { int cnt = elm.getParameterCount(); for (int i = 0; i < cnt; i++) { NameValuePair nvp = elm.getParameter(i); String nvp_name = nvp.getName(); String nvp_value = nvp.getValue(); if (nvp_name.equals(HttpRestProtocolWrapper.BOUNDARY)) { boundaryVal = nvp_value; break; } } } // Best to return at this point if we can't // determine the boundary to parse the multi-part form if (boundaryVal == null) { throw new ClientDetectedVersionMismatchedServerResponseException( "unable to extract boundary parameter", request, response); } inStream = response.getEntity().getContent(); byte[] msParam = boundaryVal.getBytes(Charset.forName("UTF-8")); MultipartStream multipartStream = new MultipartStream(inStream, msParam, DEFAULT_BOUNDARY_BUFSIZE, null); // Parse the request boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { String header = multipartStream.readHeaders(); System.out.println("Headers: " + header); String partialPath = wrapper.extractInstanceFileRelativeFilename(header); if (partialPath == null) { log.e("putAttachments", "Server did not identify the rowPathUri for the file"); throw new ClientDetectedVersionMismatchedServerResponseException( "server did not specify rowPathUri for file", request, response); } File instFile = ODKFileUtils.getRowpathFile(sc.getAppName(), tableId, instanceId, partialPath); os = new BufferedOutputStream(new FileOutputStream(instFile)); multipartStream.readBodyData(os); os.flush(); os.close(); nextPart = multipartStream.readBoundary(); } } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); System.out.println("batchGetFilesForRow: Download file batches: Error closing output stream"); } } if (response != null) { EntityUtils.consumeQuietly(response.getEntity()); response.close(); } } }
From source file:org.rsna.ctp.servlets.LookupServlet.java
/** * The servlet method that responds to an HTTP POST. * This method interprets the posted parameters as a new addition * to the file and updates it accordingly. * It then returns an HTML page containing a new form constructed * from the new contents of the file.// w ww. j a va2 s . com * @param req The HttpRequest provided by the servlet container. * @param res The HttpResponse provided by the servlet container. */ public void doPost(HttpRequest req, HttpResponse res) { //Make sure the user is authorized to do this. String home = req.getParameter("home", "/"); if (!req.userHasRole("admin")) { res.redirect(home); return; } //Get the parameters from the form. String phi = req.getParameter("phi"); String replacement = req.getParameter("replacement"); int p, s; File file = null; try { p = Integer.parseInt(req.getParameter("p")); s = Integer.parseInt(req.getParameter("s")); file = getLookupTableFile(p, s); //Update the file if possible. synchronized (this) { if ((phi != null) && (replacement != null) && (file != null)) { Properties props = getProperties(file); phi = phi.trim(); replacement = replacement.trim(); if (!phi.equals("")) { props.setProperty(phi, replacement); saveProperties(props, file); } //Make a new page from the new data and send it out res.disableCaching(); res.setContentType("html"); res.write(getEditorPage(p, s, file, home)); res.send(); return; } else if ((req.getContentType() != null) && (req.getContentType().indexOf("multipart/form-data") >= 0)) { //determining boundary bytes int boundaryIndex = req.getContentType().indexOf("boundary="); byte[] boundary = (req.getContentType().substring(boundaryIndex + 9)).getBytes(); //initiate the multipart stream (parser @SuppressWarnings("deprecation") MultipartStream multipartStream = new MultipartStream(req.getInputStream(), boundary); //parse the data while skipping the preamble boolean nextPart = multipartStream.skipPreamble(); String fileString = null; //check if first (next) file is available if (nextPart) { //read headers (to flush out of stream) multipartStream.readHeaders(); //read body data ByteArrayOutputStream data = new ByteArrayOutputStream(); multipartStream.readBodyData(data); fileString = new String(data.toByteArray()); //see whether there is a next part (next file) nextPart = multipartStream.readBoundary(); } if (fileString != null) { //split the data according to the line breaks String[] files = null; if (fileString.contains("\r\n")) files = fileString.split("\r\n"); else if (fileString.contains("\n")) files = fileString.split("\n"); //get the number of lines int numberOfLines = files.length; //get the properties file Properties props = getProperties(file); //loop through every line in the uploaded csv file for (int i = 0; i < numberOfLines; i++) { String lookupString = files[i]; String[] lookupSplit = null; //split columns of csv based on semicolon (;) or comma (,) // as this behaviour is different for different versions of office/excel if (lookupString.contains(";")) lookupSplit = lookupString.split(";"); else if (lookupString.contains(",")) lookupSplit = lookupString.split(","); //if columns arent's split, do not continue if (lookupSplit != null) { //if first column does not contain "pts/", add it, otherwise just add the property props.setProperty(lookupSplit[0].trim(), lookupSplit[1].trim()); } else { logger.warn("Line " + i + 1 + " (starting from 1) cannot be split using semicolon or comma"); } //save the properties in the script file saveProperties(props, file); } } else { logger.warn("uploaded file is empty"); } } } res.disableCaching(); res.setContentType("html"); res.write(getEditorPage(p, s, file, home)); res.send(); return; } catch (Exception ex) { } res.setResponseCode(500); //Unable to perform the function. res.send(); }
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>. * /*w w w. j a v a2 s . c om*/ * @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; }
From source file:org.wso2.carbon.bpmn.rest.common.utils.Utils.java
public static byte[] processMultiPartFile(HttpServletRequest httpServletRequest, String contentMessage) throws IOException { //Content-Type: multipart/form-data; boundary="----=_Part_2_1843361794.1448198281814" String encoding = httpServletRequest.getCharacterEncoding(); if (encoding == null) { encoding = DEFAULT_ENCODING;/* w w w . j a v a 2s .com*/ httpServletRequest.setCharacterEncoding(encoding); } byte[] requestBodyArray = IOUtils.toByteArray(httpServletRequest.getInputStream()); if (requestBodyArray == null || requestBodyArray.length == 0) { throw new ActivitiIllegalArgumentException("No :" + contentMessage + "was found in request body."); } String requestContentType = httpServletRequest.getContentType(); StringBuilder contentTypeString = new StringBuilder(); contentTypeString.append("Content-Type: " + requestContentType); contentTypeString.append("\r"); contentTypeString.append(System.getProperty("line.separator")); byte[] contentTypeArray = contentTypeString.toString().getBytes(encoding); byte[] aggregatedRequestBodyByteArray = new byte[contentTypeArray.length + requestBodyArray.length]; System.arraycopy(contentTypeArray, 0, aggregatedRequestBodyByteArray, 0, contentTypeArray.length); System.arraycopy(requestBodyArray, 0, aggregatedRequestBodyByteArray, contentTypeArray.length, requestBodyArray.length); boolean debugEnabled = log.isDebugEnabled(); int index = requestContentType.indexOf("boundary"); if (index <= 0) { throw new ActivitiIllegalArgumentException("boundary tag not found in the request header."); } String boundaryString = requestContentType.substring(index + "boundary=".length()); boundaryString = boundaryString.replaceAll("\"", "").trim(); if (debugEnabled) { log.debug("----------Content-Type:-----------\n" + httpServletRequest.getContentType()); log.debug("\n\n\n\n"); log.debug("\n\n\n\n----------Aggregated Request Body:-----------\n" + new String(aggregatedRequestBodyByteArray)); log.debug("boundaryString:" + boundaryString); } byte[] boundary = boundaryString.getBytes(encoding); ByteArrayInputStream content = new ByteArrayInputStream(aggregatedRequestBodyByteArray); MultipartStream multipartStream = new MultipartStream(content, boundary, aggregatedRequestBodyByteArray.length, null); boolean nextPart = multipartStream.skipPreamble(); if (debugEnabled) { log.debug(nextPart); } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] byteArray = null; // Get first file in the map, ignore possible other files while (nextPart) { // if (debugEnabled) { String header = multipartStream.readHeaders(); printHeaders(header); } multipartStream.readBodyData(byteArrayOutputStream); byteArray = byteArrayOutputStream.toByteArray(); nextPart = multipartStream.readBoundary(); } return byteArray; }