|
| 1 | +package express.multipart; |
| 2 | + |
| 3 | +import java.io.ByteArrayOutputStream; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStream; |
| 6 | +import java.util.Arrays; |
| 7 | + |
| 8 | +public class MultiPartStream { |
| 9 | + |
| 10 | + private final ByteArrayOutputStream BUFFER = new ByteArrayOutputStream(); |
| 11 | + private final InputStream IS; |
| 12 | + private final byte[] BOUNDARY; |
| 13 | + private final long MAX_SIZE; |
| 14 | + |
| 15 | + public MultiPartStream(InputStream body, byte[] boundary, long maxSize) { |
| 16 | + this.IS = body; |
| 17 | + this.BOUNDARY = boundary; |
| 18 | + this.MAX_SIZE = maxSize; |
| 19 | + } |
| 20 | + |
| 21 | + public MultiPartData read() throws IOException { |
| 22 | + byte[] buffer = new byte[BOUNDARY.length]; |
| 23 | + ByteArrayOutputStream b = new ByteArrayOutputStream(); |
| 24 | + String head = null; |
| 25 | + |
| 26 | + int i; // Read index |
| 27 | + int il = 0; // Last byte |
| 28 | + int boundaryIndex = 0; // Boundary index to detect boundary |
| 29 | + |
| 30 | + // Read up to next boundary |
| 31 | + while ((i = IS.read()) != -1) { |
| 32 | + |
| 33 | + // Check if the byte is a boundary start |
| 34 | + if ((byte) i == BOUNDARY[boundaryIndex]) { |
| 35 | + buffer[boundaryIndex] = (byte) i; |
| 36 | + boundaryIndex++; |
| 37 | + |
| 38 | + // Check if the boundary is fully matched |
| 39 | + if (boundaryIndex == BOUNDARY.length) |
| 40 | + break; |
| 41 | + |
| 42 | + } else { |
| 43 | + |
| 44 | + // Check if the buffer contains data |
| 45 | + if (boundaryIndex > 0) |
| 46 | + b.write(Arrays.copyOf(buffer, boundaryIndex - 1)); |
| 47 | + b.write(i); |
| 48 | + |
| 49 | + // Check if the end of the head is reached |
| 50 | + if (head == null && i == '\n' && il == '\r') { |
| 51 | + head = new String(b.toByteArray()); |
| 52 | + b.reset(); |
| 53 | + } else if (head != null) { |
| 54 | + |
| 55 | + // Check if there is an limit |
| 56 | + if (MAX_SIZE > 0 && b.size() > MAX_SIZE) { |
| 57 | + return new MultiPartData(MultiPartStatus.OUT_OF_SIZE, head, new byte[0]); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // Reset index, save last byte |
| 62 | + boundaryIndex = 0; |
| 63 | + il = i; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + // Check if the end is reached |
| 68 | + if (i == -1) |
| 69 | + return null; |
| 70 | + |
| 71 | + if (b.size() == 0) |
| 72 | + return read(); |
| 73 | + |
| 74 | + return new MultiPartData(MultiPartStatus.OK, head, b.toByteArray()); |
| 75 | + } |
| 76 | + |
| 77 | + |
| 78 | +} |
0 commit comments