Related
I am using retrofit 2 multipart for high quality Image upload (around 12 MB image). It works fine if I uses a Mobile Phone. But when I use Tablet it does not work. Can anyone tell me, what am I doing wrong here?
Here is my code:
public interface ApiDataService {
#Multipart
#POST("API Path Here")
Call<UploadImageResponse> Upload(#Header(Constants.KEY_AUTHORIZATION) String authorization,
#Part MultipartBody.Part file,
#Part("userId") RequestBody userId);
}
public class RetrofitInstance {
private static Retrofit retrofit = null;
public static Retrofit getInstance(){
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100,TimeUnit.SECONDS).build();
if(retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Then I am using following method to Upload Image on server:
public void callUploadImageApi(String token, String fileName, String userId){
ApiDataService apiDataService = RetrofitInstance.getInstance().create(ApiDataService.class);
token = "Bearer "+ token;
File path = Environment.getExternalStorageDirectory();
File dir = new File(path.getAbsolutePath() + "/MyApplication/"+ fileName);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse("image/*"),
dir
);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", dir.getName(), requestFile);
// add another part within the multipart request
RequestBody userIdString =
RequestBody.create(
okhttp3.MultipartBody.FORM, userId);
Call<UploadImageResponse> call = apiDataService.Upload(token, body, userIdString);
call.enqueue(new Callback<UploadImageResponse>() {
#Override
public void onResponse(Call<UploadImageResponse> call, Response<UploadImageResponse> response) {
if (response.body() != null) {
//success code here
}
}
#Override
public void onFailure(Call<UploadImageResponse> call, Throwable t) {
//failure code here
}
});
}
Thanks in advance for helping me...
Android beginner here.
I am having an issue with Multipart POST request.
I am calling my API using POSTMAN and it returns code :200
but when i am calling it from my Application, it returns 503.
I found out that this can happen because POSTMAN sends it as multipart by default.
I looked through a lot of answers here but i couldn't relate them to my code.
How do i convert my current request into a multipart request?
Here is my interface:
#Multipart
#POST
Call<JsonObject> Login(#Url String url, #Body JsonObject LoginData);
My Interface is as follows :
public Call<JsonObject> Logincall(String teller_ID,String password,String ...}
/*somewhere around here i must do MultipartBody.Part...cant figure out where and how */
RetrofitAPI retrofitAPIObj = RETROBUILDER.create(RetrofitAPI.class);
JsonObject LoginData=new JsonObject();
LoginData.addProperty("teller_ID",teller_ID);
LoginData.addProperty("password",password);
LoginData.addProperty("branch",branch);
LoginData.addProperty("terminal",terminal);
LoginData.addProperty("isSecure",isSecure);
return retrofitAPIObj.Login(RetrofitURL.LOGIN, LoginData);
}
Thanks in advance
You can Call Api Format Like This There is parameter type Like JsonObject in post Method
Call<UploadHeadPicResponseModel> uploadHeadPic(#Part MultipartBody.Part file, #Part("json") RequestBody json);
public void doUploadHeadPic(#NonNull String filePath) {
if (!MNetworkUtil.isNetworkAvailable()) {
MToastUtil.show("网络不能连接");
return;
}
File file = new File(filePath);
String json = new Gson().toJson(new UploadHeadPicRequestModel());
if (!file.exists()) {
MToastUtil.show("文件不存在");
return;
}
progressDialog.show();
avatarSimpleDraweeView.setEnabled(false);
MApiManager.getService().uploadHeadPic(
MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)),
RequestBody.create(MediaType.parse("multipart/form-data"), json))
.enqueue(new OnRetrofitCallbackListener<UploadHeadPicResponseModel>(mActivity) {
#Override
public void onSuccess(UploadHeadPicResponseModel responseModel) {
progressDialog.dismiss();
avatarSimpleDraweeView.setEnabled(true);
if (responseModel != null) {
String serverAvatarUrl = responseModel.data.headPicPath;
if (!TextUtils.isEmpty(serverAvatarUrl)) {
UserModel userModel = MUserManager.getInstance().getUser();
if (userModel != null) {
userModel.setAvatarUrl(serverAvatarUrl);
MUserManager.getInstance().updateOrInsertUserInfo(userModel);
MToastUtil.show("上传头像成功");
}
}
}
}
#Override
public void onFailure(int status, String failureMsg) {
progressDialog.dismiss();
avatarSimpleDraweeView.setEnabled(true);
MToastUtil.show((TextUtils.isEmpty(failureMsg) ? "上传失败" : failureMsg) + " : " + status);
}
});
}
you can create a multipart Body with additional properties by following.
public MultipartBody createMultiPartBody(){
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("teller_ID",teller_ID);
builder.addFormDataPart("password",password);
builder.addFormDataPart("branch",branch);
builder.addFormDataPart("terminal",terminal);
builder.addFormDataPart("isSecure",isSecure);
MultipartBody requestBody = builder.build();
return requestBody;
}
Now, by calling this method, you will be getting multipartBody which you can parse by following code.
public static void uploadCropImage(String url, RequestBody requestBody, Callback<BasicResponse> callback) {
UploadMultiPartData uploadMultipartData = retrofit.create(UploadMultiPartData.class);
Call<ResponseType> call = uploadCropImageApi.uploadCropImage(url, requestBody);
call.enqueue(callback);
}
this is the interface.
public interface UploadMultiPartData {
#POST(UPLOAD_URL)
Call<ResponseType> uploadMultiPartData(
#Url String url,
#Body RequestBody requestBody);
}
I am new to android .
I want to upload image as form data using Retrofit Post method.
I am using com.squareup.retrofit2:retrofit:2.3.0
This is my request body.
**Make interface like this add "MultipartBody.Part" in request and set your image path as post method and you can upload image using retrofit use this networkclient class to create retrofit instance **
public class NetworkClient {
private static final String BASE_URL = "";
private static Retrofit retrofit;
public static Retrofit getRetrofitClient(Context context) {
if (retrofit == null) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public interface UploadAPIs {
#Multipart
#POST("/upload")
Call<ResponseBody> uploadImage(#Part MultipartBody.Part file, #Part("name") RequestBody requestBody);
}
private void uploadToServer(String filePath) {
Retrofit retrofit = NetworkClient.getRetrofitClient(this);
UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);
//Create a file object using file path
File file = new File(filePath);
// Create a request body with file and image media type
RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
// Create MultipartBody.Part using file request-body,file name and part name
MultipartBody.Part part = MultipartBody.Part.createFormData("upload", file.getName(), fileReqBody);
//Create request body with text description and text media type
RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");
//
Call call = uploadAPIs.uploadImage(part, description);
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
}
#Override
public void onFailure(Call call, Throwable t) {
}
});
}
Try this
#Multipart
#POST(Global.updateProfilePicture)
Call<YOUR_RESPONSE_MODEL> updatePicture(#Header("Authorization") String authorization, #PartMap Map<String, RequestBody> params);
And API call should be like this
public void updatePic(String senderID, String receiverID, String type, File photo) {
mProgressDialog.show();
final Map<String, RequestBody> map = new HashMap<>();
try {
RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), photo);
map.put("image\"; filename=\"" + photo.getName() + "\"", fileBody);
} catch (Exception e) {
e.printStackTrace();
}
map.put("sender_id", RequestBody.create(MediaType.parse("multipart/form-data"), senderID));
map.put("receiver_id", RequestBody.create(MediaType.parse("multipart/form-data"), receiverID));
map.put("type", RequestBody.create(MediaType.parse("multipart/form-data"), type));
Call<YOUR_RESPONSE_MODEL> call = mApiInterface.updatePicture(ACCESS_TOKEN, map);
call.enqueue(new Callback<YOUR_RESPONSE_MODEL>() {
#Override
public void onResponse(#NonNull Call<YOUR_RESPONSE_MODEL> call, #NonNull Response<YOUR_RESPONSE_MODEL> response) {
if (mContext != null) {
mProgressDialog.dismiss();
// Dismiss Dialog
}
}
#Override
public void onFailure(#NonNull Call<YOUR_RESPONSE_MODEL> call, #NonNull Throwable t) {
if (mContext != null) {
mProgressDialog.dismiss();
}
}
});
}
I got output by doing request as following
UploadAPI Interface
`
#Multipart
#Headers({"TOKEN:XXXX"})
#POST("/api/messages/image")Call<ImageResult>uploadImage(#Part("sender_id")RequestBody sender_id,#Part("receiver_id")RequestBody receiver_id,#Part("type")RequestBody type,#Part MultipartBody.Part image);`
And Following is Method Code, I tried
`
private void uploadToServer(String filePath)
{
Retrofit retrofit = NetworkClient.getRetrofitClient(this, sendImageMsgURL);
UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);
File file = new File(filePath);
MultipartBody.Part requestImage = null;
RequestBody requestFile = RequestBody.create(MediaType.parse("mutlipart/form-
data"),file);
requestImage = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
RequestBody sender_id = RequestBody.create(MediaType.parse("multipart/form-data"),
currentID);
RequestBody receiver_id = RequestBody.create(MediaType.parse("multipart/form-data"),
otherID);
RequestBody type = RequestBody.create(MediaType.parse("multipart/form-data"), "image");
Call<ImageResult> call = uploadAPIs.uploadImage(sender_id, receiver_id, type,
requestImage);
call.enqueue(new Callback<ImageResult>()
{
private Call<ImageResult> call;
private Response<ImageResult> response;
#Override
public void onResponse(Call<ImageResult> call, Response<ImageResult> response)
{
this.call = call;
this.response = response;
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("Error--------- :", t.getMessage());
}
});
}`
I have an image of postman like below. How can I do the same thing in Retrofit 2?
I've declared the interface like this:
#Multipart
#POST("/api/Pharmarcy/UploadImage")
Call<ResponseBody> uploadPrescriptionImage(
#Query("accessToken") String token,
#Query("pharmarcyRequestId") int pharmacyRequestedId,
#Part MultipartBody.Part image);
#Multipart
#POST("user/updateprofile")
Observable<ResponseBody> updateProfile(#Part("user_id") RequestBody id,
#Part("full_name") RequestBody fullName,
#Part MultipartBody.Part image,
#Part("other") RequestBody other);
//pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// add another part within the multipart request
RequestBody fullName =
RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");
service.updateProfile(id, fullName, body, other);
Look at the way I am passing the multipart and string params. Hope this will help you!
For those with an inputStream, you can upload inputStream using Multipart.
#Multipart
#POST("pictures")
suspend fun uploadPicture(
#Part part: MultipartBody.Part
): NetworkPicture
Then in perhaps your repository class:
suspend fun upload(inputStream: InputStream) {
val part = MultipartBody.Part.createFormData(
"pic", "myPic", RequestBody.create(
MediaType.parse("image/*"),
inputStream.readBytes()
)
)
uploadPicture(part)
}
If your backend does not allow multipart, you can convert the input stream into bytes and send the byte array as the request body, like so.
// In your service
#PUT
suspend fun s3Upload(
#Header("Content-Type") mime: String,
#Url uploadUrl: String,
#Body body: RequestBody
)
// In your repository
val body = RequestBody.create(MediaType.parse("application/octet"), inputStream.readBytes())
networkService.s3Upload(mime, url, body)
To get an input stream you can do something like so.
In your fragment or activity, you need to create an image picker that returns an InputStream. The advantage of an InputStream is that it can be used for files on the cloud like google drive and dropbox.
Call pickImagesLauncher.launch("image/*") from a View.OnClickListener or onOptionsItemSelected. (See Activity Result APIs).
private val pickImagesLauncher =
registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
uri?.let {
val stream = contentResolver.openInputStream(it)
itemViewModel.uploadPicture(stream)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
btn.setOnClickListener {
pickImagesLauncher.launch("image/*")
}
}
Upload Image See Here click This Link
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class AppConfig {
private static String BASE_URL = "http://mushtaq.16mb.com/";
static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
========================================================
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
interface ApiConfig {
#Multipart
#POST("retrofit_example/upload_image.php")
Call<ServerResponse> uploadFile(#Part MultipartBody.Part file,
#Part("file") RequestBody name);
/*#Multipart
#POST("ImageUpload")
Call<ServerResponseKeshav> uploadFile(#Part MultipartBody.Part file,
#Part("file") RequestBody name);*/
#Multipart
#POST("retrofit_example/upload_multiple_files.php")
Call<ServerResponse> uploadMulFile(#Part MultipartBody.Part file1,
#Part MultipartBody.Part file2);
}
I totally agree with #tir38 and #android_griezmann. This would be the version in Kotlin:
interface servicesEndPoint {
#Multipart
#POST("user/updateprofile")
fun updateProfile(#Part("user_id") id:RequestBody, #Part("full_name") fullName:RequestBody, #Part image: MultipartBody.Part, #Part("other") other:RequestBody): Single<UploadPhotoResponse>
companion object {
val API_BASE_URL = "YOUR_URL"
fun create(): servicesPhotoEndPoint {
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(API_BASE_URL)
.build()
return retrofit.create(servicesPhotoEndPoint::class.java)
}
}
}
// Pass it like this
val file = File(RealPathUtils.getRealPathFromURI_API19(context, uri))
val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
// MultipartBody.Part is used to send also the actual file name
val body: MultipartBody.Part = MultipartBody.Part.createFormData("image", file.name, requestFile)
// Add another part within the multipart request
val fullName: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name")
servicesEndPoint.create().updateProfile(id, fullName, body, fullName)
To obtain the real path, use RealPathUtils. Check this class in the answers of #Harsh Bhavsar in this question: How to get the Full file path from URI.
To getRealPathFromURI_API19, you need permissions of READ_EXTERNAL_STORAGE.
Using Retrofit 2.0 you may use this:
#Multipart
#POST("uploadImage")
Call<ResponseBody> uploadImage(#Part("file\"; fileName=\"myFile.png\" ")RequestBody requestBodyFile, #Part("image") RequestBody requestBodyJson);
Make a request:
File imgFile = new File("YOUR IMAGE FILE PATH");
RequestBody requestBodyFile = RequestBody.create(MediaType.parse("image/*"), imgFile);
RequestBody requestBodyJson = RequestBody.create(MediaType.parse("text/plain"),
retrofitClient.getJsonObject(uploadRequest));
//make sync call
Call<ResponseBody> uploadBundle = uploadImpl.uploadImage(requestBodyFile, requestBodyJson);
Response<BaseResponse> response = uploadBundle.execute();
please refer https://square.github.io/retrofit/
#Multipart
#POST(Config.UPLOAD_IMAGE)
Observable<Response<String>> uploadPhoto(#Header("Access-Token") String header, #Part MultipartBody.Part imageFile);
And you can call this api like this:
public void uploadImage(File file) {
// create multipart
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// upload
getViewInteractor().showProfileUploadingProgress();
Observable<Response<String>> observable = api.uploadPhoto("",body);
// on Response
subscribeForNetwork(observable, new ApiObserver<Response<String>>() {
#Override
public void onError(Throwable e) {
getViewInteractor().hideProfileUploadingProgress();
}
#Override
public void onResponse(Response<String> response) {
if (response.code() != 200) {
Timber.d("error " + response.code());
return;
}
getViewInteractor().hideProfileUploadingProgress();
getViewInteractor().onProfileImageUploadSuccess(response.body());
}
});
}
Retrofit 2.0 solution
#Multipart
#POST(APIUtils.UPDATE_PROFILE_IMAGE_URL)
public Call<CommonResponse> requestUpdateImage(#PartMap Map<String, RequestBody> map);
and
Map<String, RequestBody> params = new HashMap<>();
params.put("newProfilePicture" + "\"; filename=\"" + FilenameUtils.getName(file.getAbsolutePath()), RequestBody.create(MediaType.parse("image/jpg"), file));
Call<CommonResponse> call = request.requestUpdateImage(params);
you can use
image/jpg
image/png
image/gif
It is quite easy. Here is the API Interface
public interface Api {
#Multipart
#POST("upload")
Call<MyResponse> uploadImage(#Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, #Part("desc") RequestBody desc);
}
And you can use the following code to make a call.
private void uploadFile(File file, String desc) {
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
//The gson builder
Gson gson = new GsonBuilder()
.setLenient()
.create();
//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//creating our api
Api api = retrofit.create(Api.class);
//creating a call and calling the upload image method
Call<MyResponse> call = api.uploadImage(requestFile, descBody);
//finally performing the call
call.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
Source: Retrofit Upload File Tutorial.
If you want to send image with more different parameters in Multipart/formData then use this below code. It will solve your Problem.
` **1) Put this line above onCreate() method.**
File selectedFile = null;
**2) In onActivityResult() method of Camera Intent put this below code -**
final Bitmap photo = (Bitmap) data.getExtras().get("data");
imageViewPhoto.setImageBitmap(photo);
selectedFile = new File(this.getFilesDir(), "image" + ".jpg");
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(selectedFile);
photo.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
**3) In API Interface Class -**
#Multipart
#POST("photouploadWithdata.php")
Call<YourResponseModal> startDuty(#PartMap HashMap<String, RequestBody> map, #Part MultipartBody.Part image);
**4) In Activity when you call API-**
RequestBody tokens = RequestBody.create(MediaType.parse("multipart/form-data"), token);
RequestBody dates = RequestBody.create(MediaType.parse("multipart/form-data"), date);
RequestBody times = RequestBody.create(MediaType.parse("multipart/form-data"), time);
RequestBody latitudes = RequestBody.create(MediaType.parse("multipart/form-data"), latitude);
RequestBody longitudes = RequestBody.create(MediaType.parse("multipart/form-data"), longitude);
MultipartBody.Part image = MultipartBody.Part.createFormData("avatar", selectedFile.getName(),
RequestBody.create(MediaType.parse(URLConnection.guessContentTypeFromName(selectedFile.getName())), selectedFile));
HashMap<String, RequestBody> map = new HashMap<>();
map.put("token", tokens);
map.put("date", dates);
map.put("time_in", times);
map.put("latitude", latitudes);
map.put("longitude", longitudes);
RetrofitAPI retrofitAPI = APIClient.getRetrofitInstance().create(RetrofitAPI.class);
Call<StartDutyResponseModal> call = retrofitAPI.startDuty(map, image);
call.enqueue(new Callback<StartDutyResponseModal>() {
#Override
public void onResponse(Call<StartDutyResponseModal> call, Response<StartDutyResponseModal> response) {
if (response.body().getStatus() == true){
progressBar.setVisibility(View.GONE);
Intent intent = new Intent(StartDutyActivity.this, StoreListActivity.class);
startActivity(intent);
finish();
}
else {
progressBar.setVisibility(View.GONE);
AppUtils.showToast(response.body().getMessage(), StartDutyActivity.this);
}
}
#Override
public void onFailure(Call<StartDutyResponseModal> call, Throwable t) {
progressBar.setVisibility(View.GONE);
AppUtils.showToast(t.getMessage(),StartDutyActivity.this);
}
});
}
`
I'm trying to down/upload a file with retrofit 2 but can't find any tutorials examples on how to do so.
My code for downloading is:
#GET("documents/checkout")
public Call<File> checkout(#Query(value = "documentUrl") String documentUrl, #Query(value = "accessToken") String accessToken, #Query(value = "readOnly") boolean readOnly);
and
Call<File> call = RetrofitSingleton.getInstance(serverAddress)
.checkout(document.getContentUrl(), apiToken, readOnly[i]);
call.enqueue(new Callback<File>() {
#Override
public void onResponse(Response<File> response,
Retrofit retrofit) {
String fileName = document.getFileName();
try {
System.out.println(response.body());
long fileLength = response.body().length();
InputStream input = new FileInputStream(response.body());
File path = Environment.getExternalStorageDirectory();
File file = new File(path, fileName);
BufferedOutputStream output = new BufferedOutputStream(
new FileOutputStream(file));
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
} catch (IOException e) {
String logTag = "TEMPTAG";
Log.e(logTag, "Error while writing file!");
Log.e(logTag, e.toString());
}
}
#Override
public void onFailure(Throwable t) {
// TODO: Error handling
System.out.println(t.toString());
}
});
I've tried with Call and Call but nothing seems to work.
The server-side code writes the file's bytes into HttpServletResponse's output stream after setting the headers and mime type correctly.
What am I doing wrong?
Finally, the upload code:
#Multipart
#POST("documents/checkin")
public Call<String> checkin(#Query(value = "documentId") String documentId, #Query(value = "name") String fileName, #Query(value = "accessToken") String accessToken, #Part("file") RequestBody file);
and
RequestBody requestBody = RequestBody.create(MediaType.parse(document.getMimeType()), file);
Call<String> call = RetrofitSingleton.getInstance(serverAddress).checkin(documentId, document.getFileName(), apiToken, requestBody);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Response<String> response, Retrofit retrofit) {
System.out.println(response.body());
}
#Override
public void onFailure(Throwable t) {
System.out.println(t.toString());
}
});
Thanks!
Edit:
After the answer, downloading only yields a corrupted file (without the #Streaming), uploading doesn't as well. When I use the above code, the server returns a 400 error. After changing it to
RequestBody requestBody = RequestBody.create(MediaType.parse(document.getMimeType()), file);
MultipartBuilder multipartBuilder = new MultipartBuilder();
multipartBuilder.addFormDataPart("file", document.getFileName(), requestBody);
Call<String> call = RetrofitSingleton.getInstance(serverAddress).checkin(documentId, document.getFileName(), apiToken, multipartBuilder.build());
, the request executes but the backend doesn't seem to receive a file.
Backend code:
#RequestMapping(value = "/documents/checkin", method = RequestMethod.POST)
public void checkInDocument(#RequestParam String documentId,
#RequestParam String name, #RequestParam MultipartFile file,
#RequestParam String accessToken, HttpServletResponse response)
What am I doing wrong? I was able to use the backend from plain Java with the Apache HttpClient:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", new File("E:\\temp\\test.jpg"));
HttpEntity httpEntity = builder.build();
System.out.println("HttpEntity " + EntityUtils.toString(httpEntity.));
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(httpEntity);
Edit v2
For anyone interested, both up- and downloading work now: These are the solutions:
Service:
#GET("documents/checkout")
public Call<ResponseBody> checkout(#Query(value = "documentUrl") String documentUrl, #Query(value = "accessToken") String accessToken, #Query(value = "readOnly") boolean readOnly);
#Multipart
#POST("documents/checkin")
public Call<String> checkin(#Query(value = "documentId") String documentId, #Query(value = "name") String fileName, #Query(value = "accessToken") String accessToken, #Part("file") RequestBody file);
Download Code:
Call<ResponseBody> call = RetrofitSingleton.getInstance(serverAddress)
.checkout(document.getContentUrl(), apiToken, readOnly[i]);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response,
Retrofit retrofit) {
String fileName = document.getFileName();
try {
File path = Environment.getExternalStorageDirectory();
File file = new File(path, fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
IOUtils.write(response.body().bytes(), fileOutputStream);
} catch (IOException e) {
Log.e(logTag, "Error while writing file!");
Log.e(logTag, e.toString());
}
}
#Override
public void onFailure(Throwable t) {
// TODO: Error handling
System.out.println(t.toString());
}
});
Upload Code:
Call<String> call = RetrofitSingleton
.getInstance(serverAddress).checkin(documentId,
document.getFileName(), apiToken,
multipartBuilder.build());
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Response<String> response,
Retrofit retrofit) {
// Handle response here
}
#Override
public void onFailure(Throwable t) {
// TODO: Error handling
System.out.println("Error");
System.out.println(t.toString());
}
});
For downloading, you can use ResponseBody as your return type --
#GET("documents/checkout")
#Streaming
public Call<ResponseBody> checkout(#Query("documentUrl") String documentUrl, #Query("accessToken") String accessToken, #Query("readOnly") boolean readOnly);
and you can get the ResponseBody input stream in your call back --
Call<ResponseBody> call = RetrofitSingleton.getInstance(serverAddress)
.checkout(document.getContentUrl(), apiToken, readOnly[i]);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response,
Retrofit retrofit) {
String fileName = document.getFileName();
try {
InputStream input = response.body().byteStream();
// rest of your code
Your upload looks okay at first glance if you server handles multipart messages correctly. Is it working? If not, can you explain the failure mode? You also might be able to simplify by not making it multipart. Remove the #Multipart annotation and convert #Path to #Body --
#POST("documents/checkin")
public Call<String> checkin(#Query("documentId") String documentId, #Query("name") String fileName, #Query("accessToken") String accessToken, #Body RequestBody file);
I am using retrofit 2.0.0-beta2 and I had an issue uploading image by using multipart request. I solved it by using this answer: https://stackoverflow.com/a/32796626/2915075
The key for me was to use standard POST with MultipartRequestBody instead of #Multipart annotated request.
Here is my code:
Retrofit service class
#POST("photo")
Call<JsonElement> uploadPhoto(#Body RequestBody imageFile, #Query("sessionId"));
Usage from activity, fragment:
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), imageFile);
MultipartBuilder multipartBuilder = new MultipartBuilder();
multipartBuilder.addFormDataPart("photo", imageFile.getName(), fileBody);
RequestBody fileRequestBody = multipartBuilder.build();
//call
mRestClient.getRetrofitService().uploadProfilePhoto(fileRequestBody, sessionId);
i have the same problems, and i found a solution to upload files, that described here
Is it possible to show progress bar when upload image via Retrofit 2
Also I had this problem, This is how i try to solve my problem (RETROFIT 2 )
//1. What We Need From Server ( upload.php Script )
public class FromServer {
String result;
}
//2. Which Interface To Communicate Our upload.php Script?
public interface ServerAPI {
#Multipart
#POST("upload.php")//Our Destination PHP Script
Call<List<FromServer>> upload(
#Part("file_name") String file_name,
#Part("file") RequestBody description);
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl("http://192.168.43.135/retro/") // REMEMBER TO END with /
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//3. How To Upload
private void upload(){
ServerAPI api = ServerAPI.retrofit.create(ServerAPI.class);
File from_phone = FileUtils.getFile(Environment.getExternalStorageDirectory()+"/aa.jpg"); //org.apache.commons.io.FileUtils
RequestBody to_server = RequestBody.create(MediaType.parse("multipart/form-data"), from_phone);
api.upload(from_phone.getName(),to_server).enqueue(new Callback<List<FromServer>>() {
#Override
public void onResponse(Call<List<FromServer>> call, Response<List<FromServer>> response) {
Toast.makeText(MainActivity.this, response.body().get(0).result, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<List<FromServer>> call, Throwable t) { }
});
}
//4. upload.php
<?php
$pic = $_POST['file_name'];
$pic = str_replace("\"", "", $pic); //REMOVE " from file name
if(file_exists($pic)){unlink($pic);}
$f = fopen($pic, "w");
fwrite($f,$_POST['file']);
fclose($f);
$arr[] = array("result"=>"Done");
print(json_encode($arr));
?>
You can refer tutorial for Image Download using Retrofit 2.0
For the time being you can refer following functions for image download:
void getRetrofitImage() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitImageAPI service = retrofit.create(RetrofitImageAPI.class);
Call<ResponseBody> call = service.getImageDetails();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
try {
Log.d("onResponse", "Response came from server");
boolean FileDownloaded = DownloadImage(response.body());
Log.d("onResponse", "Image is downloaded and saved ? " + FileDownloaded);
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
Following is the file handling part image download using Retrofit 2.0
private boolean DownloadImage(ResponseBody body) {
try {
Log.d("DownloadImage", "Reading and writing file");
InputStream in = null;
FileOutputStream out = null;
try {
in = body.byteStream();
out = new FileOutputStream(getExternalFilesDir(null) + File.separator + "AndroidTutorialPoint.jpg");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
int width, height;
ImageView image = (ImageView) findViewById(R.id.imageViewId);
Bitmap bMap = BitmapFactory.decodeFile(getExternalFilesDir(null) + File.separator + "AndroidTutorialPoint.jpg");
width = 2*bMap.getWidth();
height = 6*bMap.getHeight();
Bitmap bMap2 = Bitmap.createScaledBitmap(bMap, width, height, false);
image.setImageBitmap(bMap2);
return true;
} catch (IOException e) {
Log.d("DownloadImage",e.toString());
return false;
}
}
I hope it will help. All the best. Happy Coding :)