How to upload image/file to pre signed s3 url using retrofit2/rxjava?
I am able to upload the file using pure okhttp code but not quite able to replicate it using retrofit2, I do not want entry of credentials because that isn't required in the case of okhttp so shouldn't be required here as well (I assume).
Following is my okhttp code.
val client = OkHttpClient()
val file = File(pathOfFileToSend)
val requestFile = okhttp3.RequestBody.create(okhttp3.MediaType.parse("image/jpeg"), file)
val body = MultipartBody.Builder()
for (field in mS3Params!!.post_params!!.fields) {
body.addFormDataPart(field.name ?: "", field.value ?: "")
}
body.addPart(Headers.of("Content-Disposition", "form-data; name="file""),requestFile)
val request = Request.Builder()
.url(BuildConfig.S3_IMAGE_SERVER_URL)
.post(body.build())
.build()
val response = client.newCall(request).execute()
if (!response.isSuccessful) {
//Success
} else {
//Fail
}
This above code works perfectly fine. Sharing my mS3Params for reference as well.
class S3ImageParamsResponseModel {
var action: String? = null
var card_id: String? = null
var image_url: String? = null
var post_params: PostParams? = null
class PostParams {
lateinit var fields: List<Field>
override fun toString(): String {
return "PostParams{" +
"fields=" + fields +
'}'.toString()
}
}
class Field {
var name: String? = null
var value: String? = null
override fun toString(): String {
return "Field{" +
"name='" + name + '''.toString() +
", value='" + value + '''.toString() +
'}'.toString()
}
}
override fun toString(): String {
return "S3ImageParamsResponseModel{" +
"action='" + action + '''.toString() +
", card_id='" + card_id + '''.toString() +
", image_url='" + image_url + '''.toString() +
", post_params=" + post_params!!.toString() +
'}'.toString()
}
Now I am unable to convert the above into a retrofit2/rxjava request. My code is always giving 405 exception. Here are the two trials.
Trial 1 -
val file = File(pathOfFileToSend)
Timber.d(TAG, "onRun: length=" + file.length())
val descriptionPart = RequestBody.create(MultipartBody.FORM, "imageFile")
val requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file)
val filePart = MultipartBody.Part.createFormData("photo", "imageFile",
requestFile)
val httpClient = OkHttpClient.Builder()
httpClient.addNetworkInterceptor(StethoInterceptor())
val client = httpClient.build()
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.S3_IMAGE_SERVER_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val uploadService = retrofit.create(FreshClient::class.java)
val uploads = uploadService.uploadFile(mS3Params!!.image_url!!,
descriptionPart, filePart)
uploads.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableObserver<ResponseBody>() {
override fun onComplete() {
}
override fun onError(e: Throwable) {
Timber.d("", "")
}
override fun onNext(uploadData: ResponseBody) {
Timber.d("", "")
}
})
Trial 2 -
val file = File(pathOfFileToSend)
Timber.d(TAG, "onRun: length=" + file.length())
val descriptionPart = RequestBody.create(MultipartBody.FORM, "imageFile")
val requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file)
val body = MultipartBody.Builder()
for (field in mS3Params!!.post_params!!.fields) {
body.addFormDataPart(field.name ?: "", field.value ?: "")
}
body.addPart(
Headers.of("Content-Disposition", "form-data; name="file""),
requestFile)
val httpClient = OkHttpClient.Builder()
httpClient.addNetworkInterceptor(StethoInterceptor())
val client = httpClient.build()
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.S3_IMAGE_SERVER_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val uploadService = retrofit.create(FreshClient::class.java)
val uploads = uploadService.uploadFile(mS3Params!!.image_url!!,
descriptionPart, body.build().part(0))
uploads.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableObserver<ResponseBody>() {
override fun onComplete() {
}
override fun onError(e: Throwable) {
Timber.d("", "")
}
override fun onNext(uploadData: ResponseBody) {
Timber.d("", "")
}
})
And my service in both cases is as follows -
@Multipart
@POST("")
fun uploadFile(@Url url: String,
@Part("description") description: RequestBody,
@Part file: MultipartBody.Part): Observable<ResponseBody>
Please help out how to convert a working okhttp code to retrofit2/rxjava.
kotlin rx-java retrofit2 okhttp
add a comment |
I am able to upload the file using pure okhttp code but not quite able to replicate it using retrofit2, I do not want entry of credentials because that isn't required in the case of okhttp so shouldn't be required here as well (I assume).
Following is my okhttp code.
val client = OkHttpClient()
val file = File(pathOfFileToSend)
val requestFile = okhttp3.RequestBody.create(okhttp3.MediaType.parse("image/jpeg"), file)
val body = MultipartBody.Builder()
for (field in mS3Params!!.post_params!!.fields) {
body.addFormDataPart(field.name ?: "", field.value ?: "")
}
body.addPart(Headers.of("Content-Disposition", "form-data; name="file""),requestFile)
val request = Request.Builder()
.url(BuildConfig.S3_IMAGE_SERVER_URL)
.post(body.build())
.build()
val response = client.newCall(request).execute()
if (!response.isSuccessful) {
//Success
} else {
//Fail
}
This above code works perfectly fine. Sharing my mS3Params for reference as well.
class S3ImageParamsResponseModel {
var action: String? = null
var card_id: String? = null
var image_url: String? = null
var post_params: PostParams? = null
class PostParams {
lateinit var fields: List<Field>
override fun toString(): String {
return "PostParams{" +
"fields=" + fields +
'}'.toString()
}
}
class Field {
var name: String? = null
var value: String? = null
override fun toString(): String {
return "Field{" +
"name='" + name + '''.toString() +
", value='" + value + '''.toString() +
'}'.toString()
}
}
override fun toString(): String {
return "S3ImageParamsResponseModel{" +
"action='" + action + '''.toString() +
", card_id='" + card_id + '''.toString() +
", image_url='" + image_url + '''.toString() +
", post_params=" + post_params!!.toString() +
'}'.toString()
}
Now I am unable to convert the above into a retrofit2/rxjava request. My code is always giving 405 exception. Here are the two trials.
Trial 1 -
val file = File(pathOfFileToSend)
Timber.d(TAG, "onRun: length=" + file.length())
val descriptionPart = RequestBody.create(MultipartBody.FORM, "imageFile")
val requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file)
val filePart = MultipartBody.Part.createFormData("photo", "imageFile",
requestFile)
val httpClient = OkHttpClient.Builder()
httpClient.addNetworkInterceptor(StethoInterceptor())
val client = httpClient.build()
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.S3_IMAGE_SERVER_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val uploadService = retrofit.create(FreshClient::class.java)
val uploads = uploadService.uploadFile(mS3Params!!.image_url!!,
descriptionPart, filePart)
uploads.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableObserver<ResponseBody>() {
override fun onComplete() {
}
override fun onError(e: Throwable) {
Timber.d("", "")
}
override fun onNext(uploadData: ResponseBody) {
Timber.d("", "")
}
})
Trial 2 -
val file = File(pathOfFileToSend)
Timber.d(TAG, "onRun: length=" + file.length())
val descriptionPart = RequestBody.create(MultipartBody.FORM, "imageFile")
val requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file)
val body = MultipartBody.Builder()
for (field in mS3Params!!.post_params!!.fields) {
body.addFormDataPart(field.name ?: "", field.value ?: "")
}
body.addPart(
Headers.of("Content-Disposition", "form-data; name="file""),
requestFile)
val httpClient = OkHttpClient.Builder()
httpClient.addNetworkInterceptor(StethoInterceptor())
val client = httpClient.build()
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.S3_IMAGE_SERVER_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val uploadService = retrofit.create(FreshClient::class.java)
val uploads = uploadService.uploadFile(mS3Params!!.image_url!!,
descriptionPart, body.build().part(0))
uploads.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableObserver<ResponseBody>() {
override fun onComplete() {
}
override fun onError(e: Throwable) {
Timber.d("", "")
}
override fun onNext(uploadData: ResponseBody) {
Timber.d("", "")
}
})
And my service in both cases is as follows -
@Multipart
@POST("")
fun uploadFile(@Url url: String,
@Part("description") description: RequestBody,
@Part file: MultipartBody.Part): Observable<ResponseBody>
Please help out how to convert a working okhttp code to retrofit2/rxjava.
kotlin rx-java retrofit2 okhttp
add a comment |
I am able to upload the file using pure okhttp code but not quite able to replicate it using retrofit2, I do not want entry of credentials because that isn't required in the case of okhttp so shouldn't be required here as well (I assume).
Following is my okhttp code.
val client = OkHttpClient()
val file = File(pathOfFileToSend)
val requestFile = okhttp3.RequestBody.create(okhttp3.MediaType.parse("image/jpeg"), file)
val body = MultipartBody.Builder()
for (field in mS3Params!!.post_params!!.fields) {
body.addFormDataPart(field.name ?: "", field.value ?: "")
}
body.addPart(Headers.of("Content-Disposition", "form-data; name="file""),requestFile)
val request = Request.Builder()
.url(BuildConfig.S3_IMAGE_SERVER_URL)
.post(body.build())
.build()
val response = client.newCall(request).execute()
if (!response.isSuccessful) {
//Success
} else {
//Fail
}
This above code works perfectly fine. Sharing my mS3Params for reference as well.
class S3ImageParamsResponseModel {
var action: String? = null
var card_id: String? = null
var image_url: String? = null
var post_params: PostParams? = null
class PostParams {
lateinit var fields: List<Field>
override fun toString(): String {
return "PostParams{" +
"fields=" + fields +
'}'.toString()
}
}
class Field {
var name: String? = null
var value: String? = null
override fun toString(): String {
return "Field{" +
"name='" + name + '''.toString() +
", value='" + value + '''.toString() +
'}'.toString()
}
}
override fun toString(): String {
return "S3ImageParamsResponseModel{" +
"action='" + action + '''.toString() +
", card_id='" + card_id + '''.toString() +
", image_url='" + image_url + '''.toString() +
", post_params=" + post_params!!.toString() +
'}'.toString()
}
Now I am unable to convert the above into a retrofit2/rxjava request. My code is always giving 405 exception. Here are the two trials.
Trial 1 -
val file = File(pathOfFileToSend)
Timber.d(TAG, "onRun: length=" + file.length())
val descriptionPart = RequestBody.create(MultipartBody.FORM, "imageFile")
val requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file)
val filePart = MultipartBody.Part.createFormData("photo", "imageFile",
requestFile)
val httpClient = OkHttpClient.Builder()
httpClient.addNetworkInterceptor(StethoInterceptor())
val client = httpClient.build()
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.S3_IMAGE_SERVER_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val uploadService = retrofit.create(FreshClient::class.java)
val uploads = uploadService.uploadFile(mS3Params!!.image_url!!,
descriptionPart, filePart)
uploads.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableObserver<ResponseBody>() {
override fun onComplete() {
}
override fun onError(e: Throwable) {
Timber.d("", "")
}
override fun onNext(uploadData: ResponseBody) {
Timber.d("", "")
}
})
Trial 2 -
val file = File(pathOfFileToSend)
Timber.d(TAG, "onRun: length=" + file.length())
val descriptionPart = RequestBody.create(MultipartBody.FORM, "imageFile")
val requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file)
val body = MultipartBody.Builder()
for (field in mS3Params!!.post_params!!.fields) {
body.addFormDataPart(field.name ?: "", field.value ?: "")
}
body.addPart(
Headers.of("Content-Disposition", "form-data; name="file""),
requestFile)
val httpClient = OkHttpClient.Builder()
httpClient.addNetworkInterceptor(StethoInterceptor())
val client = httpClient.build()
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.S3_IMAGE_SERVER_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val uploadService = retrofit.create(FreshClient::class.java)
val uploads = uploadService.uploadFile(mS3Params!!.image_url!!,
descriptionPart, body.build().part(0))
uploads.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableObserver<ResponseBody>() {
override fun onComplete() {
}
override fun onError(e: Throwable) {
Timber.d("", "")
}
override fun onNext(uploadData: ResponseBody) {
Timber.d("", "")
}
})
And my service in both cases is as follows -
@Multipart
@POST("")
fun uploadFile(@Url url: String,
@Part("description") description: RequestBody,
@Part file: MultipartBody.Part): Observable<ResponseBody>
Please help out how to convert a working okhttp code to retrofit2/rxjava.
kotlin rx-java retrofit2 okhttp
I am able to upload the file using pure okhttp code but not quite able to replicate it using retrofit2, I do not want entry of credentials because that isn't required in the case of okhttp so shouldn't be required here as well (I assume).
Following is my okhttp code.
val client = OkHttpClient()
val file = File(pathOfFileToSend)
val requestFile = okhttp3.RequestBody.create(okhttp3.MediaType.parse("image/jpeg"), file)
val body = MultipartBody.Builder()
for (field in mS3Params!!.post_params!!.fields) {
body.addFormDataPart(field.name ?: "", field.value ?: "")
}
body.addPart(Headers.of("Content-Disposition", "form-data; name="file""),requestFile)
val request = Request.Builder()
.url(BuildConfig.S3_IMAGE_SERVER_URL)
.post(body.build())
.build()
val response = client.newCall(request).execute()
if (!response.isSuccessful) {
//Success
} else {
//Fail
}
This above code works perfectly fine. Sharing my mS3Params for reference as well.
class S3ImageParamsResponseModel {
var action: String? = null
var card_id: String? = null
var image_url: String? = null
var post_params: PostParams? = null
class PostParams {
lateinit var fields: List<Field>
override fun toString(): String {
return "PostParams{" +
"fields=" + fields +
'}'.toString()
}
}
class Field {
var name: String? = null
var value: String? = null
override fun toString(): String {
return "Field{" +
"name='" + name + '''.toString() +
", value='" + value + '''.toString() +
'}'.toString()
}
}
override fun toString(): String {
return "S3ImageParamsResponseModel{" +
"action='" + action + '''.toString() +
", card_id='" + card_id + '''.toString() +
", image_url='" + image_url + '''.toString() +
", post_params=" + post_params!!.toString() +
'}'.toString()
}
Now I am unable to convert the above into a retrofit2/rxjava request. My code is always giving 405 exception. Here are the two trials.
Trial 1 -
val file = File(pathOfFileToSend)
Timber.d(TAG, "onRun: length=" + file.length())
val descriptionPart = RequestBody.create(MultipartBody.FORM, "imageFile")
val requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file)
val filePart = MultipartBody.Part.createFormData("photo", "imageFile",
requestFile)
val httpClient = OkHttpClient.Builder()
httpClient.addNetworkInterceptor(StethoInterceptor())
val client = httpClient.build()
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.S3_IMAGE_SERVER_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val uploadService = retrofit.create(FreshClient::class.java)
val uploads = uploadService.uploadFile(mS3Params!!.image_url!!,
descriptionPart, filePart)
uploads.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableObserver<ResponseBody>() {
override fun onComplete() {
}
override fun onError(e: Throwable) {
Timber.d("", "")
}
override fun onNext(uploadData: ResponseBody) {
Timber.d("", "")
}
})
Trial 2 -
val file = File(pathOfFileToSend)
Timber.d(TAG, "onRun: length=" + file.length())
val descriptionPart = RequestBody.create(MultipartBody.FORM, "imageFile")
val requestFile = RequestBody.create(MediaType.parse("image/jpeg"), file)
val body = MultipartBody.Builder()
for (field in mS3Params!!.post_params!!.fields) {
body.addFormDataPart(field.name ?: "", field.value ?: "")
}
body.addPart(
Headers.of("Content-Disposition", "form-data; name="file""),
requestFile)
val httpClient = OkHttpClient.Builder()
httpClient.addNetworkInterceptor(StethoInterceptor())
val client = httpClient.build()
val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.S3_IMAGE_SERVER_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
val uploadService = retrofit.create(FreshClient::class.java)
val uploads = uploadService.uploadFile(mS3Params!!.image_url!!,
descriptionPart, body.build().part(0))
uploads.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableObserver<ResponseBody>() {
override fun onComplete() {
}
override fun onError(e: Throwable) {
Timber.d("", "")
}
override fun onNext(uploadData: ResponseBody) {
Timber.d("", "")
}
})
And my service in both cases is as follows -
@Multipart
@POST("")
fun uploadFile(@Url url: String,
@Part("description") description: RequestBody,
@Part file: MultipartBody.Part): Observable<ResponseBody>
Please help out how to convert a working okhttp code to retrofit2/rxjava.
kotlin rx-java retrofit2 okhttp
kotlin rx-java retrofit2 okhttp
asked Nov 24 '18 at 6:01
AnanthAnanth
266
266
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455594%2fhow-to-upload-image-file-to-pre-signed-s3-url-using-retrofit2-rxjava%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455594%2fhow-to-upload-image-file-to-pre-signed-s3-url-using-retrofit2-rxjava%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown