通过改造上传大型Base64编码文件的正确方法是什么?

时间:2017-04-06 05:32:46

标签: java base64 retrofit2 okhttp

所以我正在使用改装2,它使用下面的okhttp。下面的代码片段可以工作,但是我收到大文件的OOM错误。 我相信这是因为我正在将文件读取为字节数组。

使用此方法的推荐方法是什么?

private void appendFileContentsToBody(Attachment attachment, MultipartBody.Builder requestBodyBuilder) throws IOException {
    File file = new File(attachment.getAbsolutePath());
    if(file.exists()){
        RequestBody attachmentPart =  RequestBody.create(null, Base64.getEncoder().encode(FileUtils.readFileToByteArray(file)));
        requestBodyBuilder.addPart(Headers.of("X-Filename", attachment.getFilename()), attachmentPart);
    }
}

1 个答案:

答案 0 :(得分:0)

您不应该在发送文件之前将文件编码到Base64中,这应该使用流来完成,这将由Retrofit为您完成。所以你的代码看起来应该是

private void appendFileContentsToBody(Attachment attachment, MultipartBody.Builder requestBodyBuilder) throws IOException {
    File file = new File(attachment.getAbsolutePath());
    if(file.exists()){
        RequestBody attachmentPart =  RequestBody.create(MediaType.parse("application/pdf"), file);
        requestBodyBuilder.addPart(Headers.of("X-Filename", attachment.getFilename()), attachmentPart);
    }
}

其中" application / pdf" - 是特定文件的MIME类型 那样你就不会受到OOM的影响。然而,这种方法可能会在后端首先实现,因为现在你的后端实现似乎适用于web-apps,因为它只是在请求体中需要编码文件。

相关问题