🎨 #4057 修复 weixin-java-common 模块中 FileUtils.imageToBase64ByStream(InputStream) 对输入流读取不完整导致 Base64 结果被截断/污染的问题
This commit is contained in:
committed by
GitHub
parent
c34ac4d326
commit
eeb37cd3ea
@@ -57,13 +57,10 @@ public class FileUtils {
|
||||
* @return base64编码
|
||||
*/
|
||||
public static String imageToBase64ByStream(InputStream in) {
|
||||
byte[] data = null;
|
||||
// 读取图片字节数组
|
||||
try {
|
||||
data = new byte[in.available()];
|
||||
in.read(data);
|
||||
// 返回Base64编码过的字节数组字符串
|
||||
return Base64.getEncoder().encodeToString(data);
|
||||
return Base64.getEncoder().encodeToString(IOUtils.toByteArray(in));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
|
||||
@@ -6,8 +6,10 @@ import org.testng.annotations.Test;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -30,5 +32,31 @@ public class FileUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testImageToBase64ByStream() {
|
||||
byte[] original = new byte[5000];
|
||||
for (int i = 0; i < original.length; i++) {
|
||||
original[i] = (byte) (i % 256);
|
||||
}
|
||||
// A stream that returns at most 16 bytes per read() call (like a network stream),
|
||||
// so a single in.read(buffer) does not fill the buffer.
|
||||
InputStream chunked = new InputStream() {
|
||||
private final ByteArrayInputStream delegate = new ByteArrayInputStream(original);
|
||||
|
||||
@Override
|
||||
public int read() {
|
||||
return delegate.read();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] b, int off, int len) {
|
||||
return delegate.read(b, off, Math.min(len, 16));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int available() {
|
||||
return delegate.available();
|
||||
}
|
||||
};
|
||||
String result = FileUtils.imageToBase64ByStream(chunked);
|
||||
assertThat(result).isEqualTo(Base64.getEncoder().encodeToString(original));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user