通過 Multipart 上傳檔案
使用 Retrofit2 註釋宣告你的介面:
public interface BackendApiClient {
@Multipart
@POST("/uploadFile")
Call<RestApiDefaultResponse> uploadPhoto(@Part("file\"; filename=\"photo.jpg\" ") RequestBody photo);
}
RestApiDefaultResponse
是包含響應的自定義類。
構建 API 的實現並將呼叫排入佇列:
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://<yourhost>/")
.client(okHttpClient)
.build();
BackendApiClient apiClient = retrofit.create(BackendApiClient.class);
RequestBody reqBody = RequestBody.create(MediaType.parse("image/jpeg"), photoFile);
Call<RestApiDefaultResponse> call = apiClient.uploadPhoto(reqBody);
call.enqueue(<your callback function>);