How to Base64-encode a file in chunks without padding in the middle
Encode A and BCD independently and the joined result breaks. Carry up to two leftover bytes forward to match the whole-file encoding.
Reproduce the boundary error
ABCD encodes to QUJDRA== as one input. Separately, A yields QQ== and BCD yields QkNE. The joined QQ==QkNE cannot be read as a single standard Base64 value. Deleting its internal padding still leaves the groups aligned to different bits.
Emit only complete groups of three
This Python generator keeps zero, one or two leftover bytes after each chunk. It prepends them to the next chunk and encodes only full three-byte groups. After the input ends, it encodes the final remainder once. The example prints QUJDRA==.
import base64
def encode_chunks(chunks):
carry = b""
for chunk in chunks:
block = carry + chunk
end = (len(block) // 3) * 3
yield base64.b64encode(block[:end])
carry = block[end:]
yield base64.b64encode(carry)
print(b"".join(encode_chunks([b"A", b"BCD"])).decode("ascii"))Test the boundaries of your stream
Split a small file at one-, two-, three- and four-byte intervals and compare the results with whole-file encoding. Include empty chunks and final remainders of one and two bytes. For a large file, send yielded pieces directly to an output stream instead of joining them in memory.