SoFunction
Updated on 2025-04-10

Android uses Retrofit to upload files in pure binary file streams

1. Background

Generally, upload files are uploaded in form. Recently, the project involves uploading file streams in non-form formats, which are divided into single file stream uploads and large file segments uploads. There is less information in this scenario, so I will record it here.

2. Introduction to the plan

2.1 Requirement Agreement

1. Upload file
API Endpoint:/service/upload
● method:PUT
● Request parameters:
    ○ filename:file name(Must-choose)
○ Request header:
    ○ Authorization:For authentication token(Must-choose)
    ○ X-Request-ID:The unique identifier for the request(Must-choose)
    ○ Upload-Offset:Offset of the current upload block(Must-choose)
        ■ unit:byte
    ○ Upload-Type:File upload method(Must-choose)
        ■ 1 Upload to album(/storage/emulated/0/Pictures/)
        ■ 2 Upload tosdcard(/sdcard/)
○ Request body
    ○ File binary data

2.2 Defining the interface

Format:/api/upload?filename=
So the interface should be defined like this:
   @PUT("/service/upload")
RequestBody): Call<ResponseBody>
   fun uploadFile(@Query("filename") filename:String,  @Body body: RequestBody):Call<ResponseBody>

2.3 Define a RequestInterceptor iterator and put the request parameters into the request header

class RequestInterceptor(val authorization:String,val requestId:String,val offset:String,val uploadType:String) : Interceptor {
    override fun intercept(chain: ): Response {
        val request = ()
        val requestBuilder = ()
        ("Authorization", authorization)
        ("X-Request-ID", requestId)
        if(()){
            ("Upload-Offset", offset)
        }
        if(()){
            ("Upload-Type", uploadType)
        }
//        ("Content-Length")
//        ("Content-Transfer-Encoding")
//        ("Content-Disposition")
        return (())
    }
}

2.4 Calling the interface

      // Create a file name request body            val requestBody = (null, file)//The first parameter passes null            val call = (token, requestId, "0", uploadType)
                .uploadFile(, requestBody)

Related libraries used:

implementation '.retrofit2:retrofit:2.9.0'
   implementation '.retrofit2:converter-gson:2.9.0'
   implementation '.okhttp3:logging-interceptor:3.14.9'

This is the article about uploading files with pure binary files using Retrofit. For more related Android, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!