gpt4 book ai didi

java - 如何发送base64格式的大文件?

转载 作者:行者123 更新时间:2023-12-04 14:50:12 24 4
gpt4 key购买 nike

我有一个 Spring & Angular 应用程序,我开发了一个服务来上传和下载文件

将从我服务器上的文件夹中获取要下载的文件(因此我将使用 FTP 将文件放入文件夹中)然后以 base64 编码并显示给用户。

用户可以下载文件,我设法通过将长 base64 字符串分成 256 字节 的小块来让用户下载大文件(我测试过在本地,即使速度仍然很慢,它也能正常工作。

问题出在我的 Spring 后端,我无法压缩 base64 字符串,我必须在我的架构中显示文件的唯一方法是返回 base64 字符串,但是当涉及到大文件时,我收到以下错误:

    Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: Java heap space

这是我用来返回 base64 字符串的服务片段:

    @Override
public List<FileDto> loadAll() {
List<FileDto> files = new ArrayList<FileDto>();

try {
File folder = new File("uploads"+ File.separator +"adminfolder");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
String directory = folder.toString() + File.separator + listOfFiles[i].getName();

String allegato = BufferedImageUtility.encodeFileToBase64Binary(directory);
String tipoFile = BufferedImageUtility.getMimeType(directory);
String estensione = "";

files.add(new FileDto("", allegato, listOfFiles[i].getName(), tipoFile, estensione));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}

这里是 encodeFileToBase64Binary() 方法:

    public static String encodeFileToBase64Binary(String fileName) {
String encodedString = "";

try {
File file = new File(fileName);
byte[] bytes = loadFile(file);
byte[] encoded = Base64.getEncoder().encode(bytes);
encodedString = new String(encoded,StandardCharsets.US_ASCII);
} catch (IOException e) {
logger.debug("errore encodeFileToBase64Binary, ", e);
throw new EFWMException(e);
}

return encodedString;
}

最佳答案

与其使用 loadFile(file) 将整个文件加载到内存中,我建议您尝试将其流式传输到 Base64 中。

试试这个编码:

  public static String encodeFileToBase64Binary(final String fileName)
{
try(final ByteArrayOutputStream out = new ByteArrayOutputStream())
{
Files.copy(Path.of(fileName), Base64.getEncoder().wrap(out));
return out.toString(StandardCharsets.US_ASCII);
}
catch (final IOException e)
{
logger.debug("errore encodeFileToBase64Binary, ", e);
throw new EFWMException(e);
}
}

关于java - 如何发送base64格式的大文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69223517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com