【问题标题】:What is the correct way to upload large Base64 encoded files with retrofit?通过改造上传大型 Base64 编码文件的正确方法是什么?
【发布时间】:2017-04-06 05:32:46
【问题描述】:

所以我正在使用下面使用 okhttp 的改造 2。下面的代码 sn-p 有效,但我收到大文件的 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);
    }
}

【问题讨论】:

    标签: java base64 retrofit2 okhttp


    【解决方案1】:

    您不应该在发送文件之前将文件编码为 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 的痛苦。然而,这种方法可能首先在后端实现,因为现在您的后端实现似乎只适用于网络应用,因为它需要在请求正文中编码文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 2017-03-11
      • 1970-01-01
      • 2016-10-11
      • 2013-07-24
      • 2012-12-04
      • 1970-01-01
      相关资源
      最近更新 更多