gpt4 book ai didi

java - 将大文件转换为Java中的base64表示;内存不足异常

转载 作者:行者123 更新时间:2023-12-02 01:30:02 27 4
gpt4 key购买 nike

我有一种情况,我需要以这种格式将对象从后端传输到前端:

{
filename: "filename",
type: "type",
src: "src",
bytes: "base64Representation"
}

对象的 bytes 属性包含存储在远程服务器存储库中的文件的 Base64 表示形式。到目前为止,我已经处理过 1-2MB 范围内的小文件,并且将文件转换为相应的 Base64 表示形式的代码可以正常工作。但现在我遇到了一些大文件(大于 100MB)的问题。我已经检查了尝试逐 block 转换文件 block 的解决方案,但仍然在过程结束时我需要将所有 block 连接在一个字符串中,在这一步我收到 OutOfMemory 异常。我还看到了一些使用 OutputStreams 的建议,但我无法应用它们,因为我需要上述格式的数据。请问有人对我如何绕过这种情况有任何建议吗?

最佳答案

您可以通过包装 response.getOutputStream() 在 servlet 中使用 OutputStream 并动态处理。我将给出一个 Spring Boot 的工作示例。我测试过,它有效。

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

@RestController
public class Base64Controller {

@RequestMapping(value = "/base64", method = RequestMethod.GET)
public void getBase64File(HttpServletResponse response) throws IOException {
response.setContentType("text/plain");
OutputStream wrap = Base64.getEncoder().wrap(response.getOutputStream());
FileInputStream fis = new FileInputStream("./temp.txt");
int bytes;
byte[] buffer = new byte[2048];
while ((bytes=fis.read(buffer)) != -1) {
wrap.write(buffer, 0, bytes);
}
fis.close();
wrap.close();
}

}

关于java - 将大文件转换为Java中的base64表示;内存不足异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56221732/

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