Base64 编码文件和内存不足错误



我有.zip文件,在上传到服务器之前,我必须对其进行Base64编码。给定文件最大可达 20 MB,这会导致内存不足异常。 我使用此代码:

public String encodeZipToBase64(File zip) {
    StringBuffer sb = new StringBuffer();
    byte fileContent[] = new byte[1024];
    try 
    {
        FileInputStream fin = new FileInputStream(zip);
        while(fin.read(fileContent) >= 0) {
             sb.append(Base64.encodeToString(fileContent, Base64.DEFAULT)); //exception here
        }
    } catch(OutOfMemoryError e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return sb.toString();
}

追加到 StringBuilder 时发生异常。我该怎么做才能解决它?

谢谢!

您应该将 HTTP 请求OutputStream作为参数传递,并直接在读取循环中写入它,而不是将整个请求作为内存中的StringBuilder进行缓冲。

最新更新