Read the data from a multipart/form-data request

@param boundary The boundary specified by the client
@return A map of the POST data.
@throws IOException If an error occurs
164259
public Map<String, Object> readMultipartData(String boundary) throws IOException {
		// Boundaries are '--' + the boundary.
		boundary = "--" + boundary;
		// Form data
		Map<String, Object> form = new HashMap<String, Object>();
		// Implementation of a reader to parse out form boundaries.
		MultipartReader reader = new MultipartReader(input, boundary);
		String l;
		while ((l = reader.readLine()) != null) {
			if (!l.startsWith(boundary) || l.startsWith(boundary) && l.endsWith("--")) {
				break;
			}
			// Read headers
			Map<String, String> props = new HashMap<String, String>();
			while ((l = reader.readLine()) != null && l.trim().length() > 0) {
				// Properties
				String key = HttpUtil.capitalizeHeader(l.substring(0, l.indexOf(':')));
				String value = l.substring(l.indexOf(':') + 1);
				if (value.charAt(0) == ' ')
					value = value.substring(1);

				props.put(key, value);
			}
			// Check if the line STILL isn't null
			if (l != null) {
				String contentDisposition = props.get(HttpHeader.CONTENT_DISPOSITION);
				Map<String, String> disposition = new HashMap<String, String>();
				String[] dis = contentDisposition.split("; ");
				for (String s : dis) {
					int eqIdx = s.indexOf('=');
					if (eqIdx != -1) {
						String key = s.substring(0, eqIdx);
						String value = s.substring(eqIdx + 1).trim();
						if (value.charAt(0) == '"') {
							value = value.substring(1, value.length() - 1);
						}
						disposition.put(key, value);
					}
				}
				String name = disposition.get("name");
				if (props.containsKey(HttpHeader.CONTENT_TYPE)) {
					String fileName = disposition.get("filename");
					// Create a temporary file, this'll hopefully be deleted
					// when the request object has finalize() called
					File tmp = File.createTempFile("upload", fileName);
					// Open an output stream to the new file
					FileOutputStream output = new FileOutputStream(tmp);
					// Read the file data right from the connection, NO MEMORY
					// CACHE.
					byte[] buffer = new byte[1024];
					while (true) {
						int read = reader.readUntilBoundary(buffer, 0, buffer.length);
						if (read == -1) {
							break;
						}
						output.write(buffer, 0, read);
					}
					// Close it
					output.close();
					// Put the temp file
					form.put(name, new HttpFileUpload(fileName, tmp));
				} else {
					String value = "";
					// String value
					while ((l = reader.readLineUntilBoundary()) != null) {
						value += l;
					}
					form.put(name, value);
				}
			}
		}
		return form;
	}
825840
public byte[] getRawData() throws IOException
    {
        int contentLength = request.getContentLength();
        if( contentLength<0 ) {
            return null;
        }
        
        byte[] buffer = new byte[contentLength];
        ServletInputStream is = request.getInputStream();
        for (int i = 0; i < contentLength; ) {
            int rLen = is.read(buffer, i, contentLength - i);
            if ( rLen == -1 ) {
                break;
            }
            
            i += rLen;
        }
        
        return buffer;
    }
182287
public static final String createBoundary() {
		final StringBuilder builder = new StringBuilder(BOUNDARY_PREFIX);
		builder.append((int) System.currentTimeMillis());
		return builder.toString();
	}
687725
@Deprecated
    public static String encodePostBody(Bundle parameters, String boundary) {
        if (parameters == null) return "";
        StringBuilder sb = new StringBuilder();

        for (String key : parameters.keySet()) {
            Object parameter = parameters.get(key);
            if (!(parameter instanceof String)) {
                continue;
            }

            sb.append("Content-Disposition: form-data; name=\"" + key +
                    "\"\r\n\r\n" + (String)parameter);
            sb.append("\r\n" + "--" + boundary + "\r\n");
        }

        return sb.toString();
    }
673879
public void write(Map<String, Object> params) throws IOException {
		LineWriter writer = new LineWriter(this.out);
		try {
			for (Map.Entry<String, Object> param: params.entrySet()) {
				writer.println(MULTIPART_BOUNDARY_SEPARATOR);

				if (param.getValue() instanceof BinaryAttachment) {
					BinaryAttachment ba = (BinaryAttachment)param.getValue();
					writer.println("Content-Disposition: form-data; name=\"" + StringUtils.urlEncode(param.getKey()) + "\"; filename=\""
							+ StringUtils.urlEncode(ba.filename) + "\"");
					writer.println("Content-Type: " + ba.contentType);
					writer.println("Content-Transfer-Encoding: binary");
					writer.println();
					writer.flush();
					// Now output the binary part to the raw stream
					int read;
					byte[] chunk = new byte[8192];
					while ((read = ba.data.read(chunk)) > 0)
						this.out.write(chunk, 0, read);
				} else {
					writer.println("Content-Disposition: form-data; name=\"" + StringUtils.urlEncode(param.getKey()) + "\"");
					writer.println();
					writer.println(StringUtils.urlEncode(param.getValue().toString()));
				}
			}

			writer.println(MULTIPART_BOUNDARY_END);
			writer.flush();
		} finally {
			writer.close();
		}
	}
669594
function createBoundary(data) {
  while (true) {
    var boundary = `----IPFSMini${Math.random() * 100000}.${Math.random() * 100000}`;
    if (data.indexOf(boundary) === -1) {
      return boundary;
    }
  }
}
1171703
public byte[] postBytes(byte[] content) throws IOException {

        if (!connection.isOpen())
            connection.open();

        connection.prepare("POST");

        OutputStream os = connection.getOutputStream();
        os.write(content);

        response = connection.readInput();
        os.close();
        return getResponseBytes();
    }
682235
public InputStream doPost(byte[] postData, String contentType) {
        this.urlConnection.setDoOutput(true);
        if (contentType != null) this.urlConnection.setRequestProperty( "Content-type", contentType );

        OutputStream out = null;
        try {
            out = this.getOutputStream();
            if(out!=null)
            {
                out.write(postData);
                out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(out!=null)
                try {
                    out.close();
                } catch (IOException e) {
                    //
                }
        }


        return (this.getInputStream());
    }
228874
private static Object readBoundary(
        ObjectInput in,
        byte header
    ) throws IOException, ClassNotFoundException {

        int past = (header & 0x1);

        if (past == 1) {
            return Boundary.infinitePast();
        }

        int future = (header & 0x2);

        if (future == 2) {
            return Boundary.infiniteFuture();
        }

        int openClosed = in.readByte();
        IntervalEdge edge;

        switch (openClosed) {
            case 0:
                edge = IntervalEdge.CLOSED;
                break;
            case 1:
                edge = IntervalEdge.OPEN;
                break;
            default:
                throw new StreamCorruptedException("Invalid edge state.");
        }

        Object t = in.readObject();
        return Boundary.of(edge, t);

    }
231512
def _get_multiparts(response):
        
        boundary = None
        for part in response.headers.get('Content-Type', '').split(';'):
            if 'boundary=' in part:
                boundary = '--{}'.format(part.split('=', 1)[1].strip('\"'))
                break

        if not boundary:
            raise ParseError("Was not able to find the boundary between objects in a multipart response")

        if response.content is None:
            return []

        response_string = response.content

        if six.PY3:
            # Python3 returns bytes, decode for string operations
            response_string = response_string.decode('latin-1')

        #  help bad responses be more multipart compliant
        whole_body = response_string.strip('\r\n')
        no_front_boundary = whole_body.strip(boundary)
        # The boundary comes with some characters

        multi_parts = []
        for part in no_front_boundary.split(boundary):
            multi_parts.append(part.strip('\r\n'))

        return multi_parts
1192539
public void readProperties(ImageInputStream in, int len, ExtendImageHeader imageHeader) throws IOException {
        int numToRead = 0;

        // get the interesting part of the marker data
        if (len >= 14) {
            numToRead = 14;
        } else if (len > 0) {
            numToRead = len;
        } else {
            numToRead = 0;
        }

        byte[] datas = new byte[numToRead];

        in.read(datas);

        len -= numToRead;

        if (numToRead >= 14 && datas[0] == 0x4A && datas[1] == 0x46 && datas[2] == 0x49 && datas[3] == 0x46
            && datas[4] == 0) {
            // Found JFIF APP0 marker: save info
            imageHeader.setSawJFIFMarker(true);
            imageHeader.setJFIFMajorVersion(datas[5]);
            imageHeader.setJFIFMinorVersion(datas[6]);
            imageHeader.setDensityUnit(datas[7]);
            imageHeader.setXDensity(datas[8] << 8);
            imageHeader.setYDensity(datas[10] << 8);

            // need check metadata info or not?
        } else if (numToRead >= 6 && datas[0] == 0x4A && datas[1] == 0x46 && datas[2] == 0x58 && datas[3] == 0x58
                   && datas[4] == 0) {
            // Found JFIF "JFXX" extension APP0 marker
            imageHeader.setSawJFXXMarker(true);
        }

        // skip any remaining data -- could be lots
        if (len > 0) {
            in.skipBytes(len);
        }
    }
904405
def parse_multipart_formdata(reader, boundary, cb):
    

    breader = BoundaryReader(reader, boundary)
    # The BoundaryReader expects a new line before the boundary string,
    # We make sure the new line exists
    breader.put(b'\r\n')
    # Clean up garbage before the first boundary
    _dummy_data = yield from breader.read()
    logger('parse_multipart_formdata').debug('_dummy_data = %r', _dummy_data)
    del _dummy_data

    breader = BoundaryReader(reader, boundary)
    line = yield from breader.readline()
    while line:
        headers = []
        while line.strip():
            header = parse_http_header(line)
            headers.append(header)
            line = yield from breader.readline()

        yield from cb(headers, breader)

        yield from breader.read()
        breader = BoundaryReader(reader, boundary)
        line = yield from breader.readline()
41129
public static byte[] computeMultipartBoundary() {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    byte[] bytes = new byte[35];
    for (int i = 0; i < bytes.length; i++) {
      bytes[i] = MULTIPART_CHARS[random.nextInt(MULTIPART_CHARS.length)];
    }
    return bytes;
  }
571913
def parse_multipart_form(body, boundary):
    '''
    '''
    files = RequestParameters()
    fields = RequestParameters()

    form_parts = body.split(boundary)
    for form_part in form_parts[1:-1]:
        file_name = None
        file_type = None
        field_name = None
        line_index = 2
        line_end_index = 0
        while not line_end_index == -1:
            line_end_index = form_part.find(b'\r\n', line_index)
            form_line = form_part[line_index:line_end_index].decode('utf-8')
            line_index = line_end_index + 2

            if not form_line:
                break

            colon_index = form_line.index(':')
            form_header_field = form_line[0:colon_index].lower()
            form_header_value, form_parameters = parse_header(
                form_line[colon_index + 2:])

            if form_header_field == 'content-disposition':
                if 'filename' in form_parameters:
                    file_name = form_parameters['filename']
                field_name = form_parameters.get('name')
            elif form_header_field == 'content-type':
                file_type = form_header_value

        post_data = form_part[line_index:-4]
        if file_name or file_type:
            file = File(type=file_type, name=file_name, body=post_data)
            if field_name in files:
                files[field_name].append(file)
            else:
                files[field_name] = [file]
        else:
            value = post_data.decode('utf-8')
            if field_name in fields:
                fields[field_name].append(value)
            else:
                fields[field_name] = [value]

    return fields, files
1257935
@Override
    public byte readByte() throws IndexOutOfBoundsException, IOException {
        final int read = internalReadBytes(1);
        if (read == -1) {
            // not sure this is really the right thing to do
            throw new IndexOutOfBoundsException();
        }
        return getByte(this.readerIndex++);
    }
1014859
private Request make(final byte[] boundary,
        final ReadableByteChannel body) throws IOException {
        final File file = File.createTempFile(
            RqMultipart.class.getName(), ".tmp"
        );
        try (WritableByteChannel channel = Files.newByteChannel(
            file.toPath(),
            StandardOpenOption.READ,
            StandardOpenOption.WRITE
        )
        ) {
            channel.write(
                ByteBuffer.wrap(
                    this.head().iterator().next().getBytes(RqMtBase.ENCODING)
                )
            );
            channel.write(
                ByteBuffer.wrap(RqMtBase.CRLF.getBytes(RqMtBase.ENCODING))
            );
            this.copy(channel, boundary, body);
        }
        return new RqTemp(file);
    }
682498
@Override
  protected Long stringToBoundary(String boundary, Integer segmentNumber)
      throws IOException {
    if (segmentRegistration.equals(SEGMENT_BOUNDARY_ASC)
        || segmentRegistration.equals(SEGMENT_BOUNDARY_DESC)) {
      if (segmentNumber == null) {
        return Long.valueOf(boundary);
      } else {
        return Math.floorDiv(Long.parseLong(boundary), segmentNumber);
      }
    } else {
      throw new IOException(
          "not available for segmentRegistration " + segmentRegistration);
    }
  }