Retrofit 2 file upload does not attach file - android

I've written a upload action on server using asp core and I've tested that with ARC and files gets received.
But when I try to upload image with Retrofit, nothing gets send. Even the form is empty:
The source Code of interface is here. The interface:
public interface QuestionWebService {
#Multipart
#POST("questionapi/uploadfiles")
Call<ResponseBody> uploadSync(#Part("fileUpload") RequestBody paramTypedFile);
}
and the usage in async task:
#Override
protected Boolean doInBackground(String... params) {
File fileToSend = new File(params[0]);
// fileToSend.renameTo()
RequestBody typedFile = RequestBody.create(MediaType.parse("image/*"), fileToSend);
Response response = restClient.getQuestionService().uploadSync(typedFile).execute();
if (response == null){
Log.e(TAG, "success send server - failed");
return false;
}
if (response.isSuccessful()) {
Log.e(TAG, "success send server - 200 status");
} else {
Log.e(TAG, "success send server - fail status - " + response.toString());
}
} catch (Exception e) {
//throw new RuntimeException(e);
Log.e(TAG,e.getMessage().toString());
return false;
}
return true;
}
Any Idea about what should I try? Where am I Going Wrong.
TG.

Finally I found the solution. I don't know the reason about why this code doesn't work but as this link says, I changed the:
public interface QuestionWebService {
#Multipart
#POST("questionapi/uploadfiles")
Call<ResponseBody> uploadSync(#Part("fileUpload") RequestBody paramTypedFile);
}
to this one:
public interface QuestionWebService {
#Multipart
#POST("questionapi/uploadfiles")
Call<ResponseBody> uploadSync(#Part("UserId") RequestBody UserId, #Part("answer") RequestBody answer, #Part MultipartBody.Part file);
}
and the usage from this:
RequestBody typedFile = RequestBody.create(MediaType.parse("image/*"), fileToSend);
Response response = restClient.getQuestionService().uploadSync(typedFile).execute();
to this one:
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), fileToSend);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("fileUpload", fileToSend.getName(), requestFile);
RequestBody userId =
RequestBody.create(
MediaType.parse("multipart/form-data"), userIdString);
// add another part within the multipart request
String answerString = "hello, this is answer speaking";
RequestBody answer =
RequestBody.create(
MediaType.parse("multipart/form-data"), answerString);
Response response = restClient.getQuestionService().uploadSync(userId, answer, body).execute();
and now every thing goes right!!!
I hope this will the others encounter same problem.
Now the data on server is a form with 2 fields, UserId and Answer, and a file named fileUpload.
TG.

Related

what is the issue in file uploading using retrofit (pdf,ppt, png,jpg) "code=500, internal server error"

enter image description hereI'm setting up the file uploading function using retrofit but I am getting internal server error. Sometime file is uploading on the server with details but response is coming in error body. I have no idea is there any problem in my code or in server side code.
I have tried different code for request body.
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("pic", file.getName(), requestFile);
File file = new File(PathHolder);
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("pic",
file.getName(), requestFile);
RequestBody userId =
RequestBody.create(MediaType.parse("text/plain"), uid);
RequestBody topic = RequestBody.create(MediaType.parse("text/plain"),
topicName);
RequestBody classID =
RequestBody.create(MediaType.parse("text/plain"), classId);
RequestBody shiftID =
RequestBody.create(MediaType.parse("text/plain"), shiftId);
Call<UploadDocumentResponse> resultCall = service.uploadImage(userId,
topic, classID, shiftID, body);
resultCall.enqueue(new Callback<UploadDocumentResponse>() {
#Override
public void onResponse(Call<UploadDocumentResponse> call,
Response<UploadDocumentResponse> response) {
progressDialog.dismiss();
onBackPressed();
UploadDocumentResponse iresponse = response.body();
// ViewDocModel Success or Fail
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), response.body().
getMsg(), Toast.LENGTH_LONG).show();
imageView.setImageDrawable(null);
imagePath = null;
}
}
#Override
public void onFailure(Call<UploadDocumentResponse> call, Throwable t)
{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "couldn't upload file,
please try
again", Toast.LENGTH_LONG).show();
}
});
// APIInterface
#Multipart
#POST("Camp/API_uploadfile.php")
Call<UploadDocumentResponse> uploadImage(#Part("uid") RequestBody uid,
#Part("topic") RequestBody
topic,
#Part("classid") RequestBody
classId,
#Part("shiftid") RequestBody
shiftId,
#Part MultipartBody.Part file);
Expected result is file should be upload on server and get response in success.
Actual result is getting internal server error and sometime getting success response message in error body.
I have solved this issue.
I was using wrong pattern of request body. I had to use multipart form data instead of text.
File file1 = new File(imageFilePathFront);
RequestBody requesFile = RequestBody.create(MediaType.parse("multipart.form-
data"), file1);
cnicFront = MultipartBody.Part.createFormData("CNIC_FRONT_IMG",
file1.getName(), requesFile);
This is the right code worked for me.

Retrofit2 - Upload photo 500 Internal Server error

I want to upload a photo using Retrofit2, but I can't get rid of 500 Internal Server error. I also get the message "reduce of empty array with no initial value". When I retrieve the uploaded photos from the server, the photo is not there. I'm using Charles Web Debugging Proxy tool to check the response.
public static void postPhoto(String participantId, String photoPath) {
try {
File photo = new File(photoPath);
ApiEndpoints api = ApiProvider.getInstance().getApiInstance();
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), photo);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", photo.getName(), reqFile);
Call<ResponseBody> call = api.uploadPhoto(participantId, body);
call.execute();
} catch (Exception e){
e.printStackTrace();
}
}
API endpoint
#Multipart
#POST("participant/{id}/image")
Call<ResponseBody> uploadPhoto(#Path("id") String id, #Part MultipartBody.Part image);

Send image with Retrofit2

I'm trying to upload an image to the server using Retrofit2, but am very unsure on how to do so.
The documentation left me a bit confused and I have tried the solution mentioned here, but it did not work for me.
Here is the code snippet I'm currently using, which doesn't send anything to the server:
// Service
#Multipart
#POST("0.1/gallery/{galleryId}/addImage/")
Call<ResponseBody> addImage(#Path("galleryId") String galleryId, #Part MultipartBody.Part image);
//Call
MultipartBody.Part imagePart = MultipartBody.Part.createFormData("image", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
Call<ResponseBody> call = service. addImage("1234567890", imagePart);
However, I'm able to do it just fine using Retrofit 1.9 with a TypedFile.
Am I doing something wrong or Retrofit2 has some issue with this sort of thing?
I've struggled for a while with this to, I ended up with this solution to finally make it work... Hopes it helps:
Map<String, RequestBody> map = new HashMap<>();
map.put("Id",Utils.toRequestBody("0"));
map.put("Name",Utils.toRequestBody("example"));
String types = path.substring((path.length() - 3), (path.length()));
File file = new File(pathOfYourFile);
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file);
map.put("file\"; filename=\"cobalt." + types + "\"", fileBody);
Call<ResponseBody> call = greenServices.upload(map);
In the greenServices interface:
#Multipart
#POST(Constants.URL_UPLOAD)
Observable<Response<ResponseBody>> uploadNew(#PartMap Map<String, RequestBody> params);
hi please check how we can send image in retrofit2.In form of part you need to send image and other data as well.
public interface ApiInterface {
#Multipart
#POST("0.1/gallery/{galleryId}/addImage/")
Call<User> checkapi (#Part("file\"; filename=\"pp.png\" ") RequestBody file , #Part("FirstName") RequestBody fname, #Part("Id") RequestBody id);
}
File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));
Call<User> call = client.editUser(AZUtils.getToken(this), fbody, name, id);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(retrofit.Response<User> response, Retrofit retrofit) {
AZUtils.printObject(response.body());
}
#Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
Thanks hope this will help you.

Send json and file with Retrofit2

I used to send POST request to server with Retrofit2:
#POST("goals")
Call<Void> postGoal(#Body Goal goal);
where Goal was object with some String/Integer fields.
Now I need to add a photo file there.
I know I need to switch to use Multipart:
#Multipart
#POST("goals")
Call<Void> postGoal(
#Part("picture") RequestBody picture
);
//...
//Instantaining picture
RequestBody.create(MediaType.parse("image/*"), path)
But how am I supposed to add previous fields ? In particular is there a way to add whole Goal object without dividing it for fields ?
for sending json and file you can follow something like this.
#Multipart
#POST("goals")
Call<JsonModel> postGoal(#Part MultipartBody.Part file, #Part("json") RequestBody json);
Now convert your Object which you want to send as a json into json using Gson.
like this.
String json = new Gson().toJson(new Goal());
File file = new File(path);
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("picture", file.getName(), requestFile);
// add another part within the multipart request
RequestBody jsonBody=
RequestBody.create(
MediaType.parse("multipart/form-data"), json);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RestApi api = retrofit.create(RestApi.class);
Call<ResponseBody> call = api.upload(jsonBody, body);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("onResponse: ", "success");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("onFailure: ", t.getLocalizedMessage());
}
});
You can add #Part with you goal like this
#Multipart
#POST("goals")
Call<Void> postGoal(
#Part("picture") RequestBody picture,
#Part("goal") RequestBody goal
);
//...
//Instantaining picture
RequestBody.create(MediaType.parse("image/*"), path)
You can find more details : retrofit-2-how-to-upload-files-to-server

Android send byte array with image using Retrofit2

I have a byte array in my application which I get from camera. I need to send it to server using Retrofit2. When I try send it I get SocketTimeoutException. I've tried also send request using browser and all works fine. Here is my retrofit service method for sending:
#Multipart
#POST("/userchange/setuserpic")
Call<AuthResponse> setUserPic(#Part("authToken") RequestBody authToken, #Part("userpic") RequestBody picture, #Part("extension") RequestBody extension);
I do sending in my service like below:
private void handleActionSetUserPic(String authToken, byte[] picture, String extension) {
RequestBody token = RequestBody.create(MediaType.parse("multipart/form-data"), authToken);
RequestBody pic = RequestBody.create(MediaType.parse("multipart/form-data"), picture);
RequestBody ext = RequestBody.create(MediaType.parse("multipart/form-data"), extension);
Call<AuthResponse> request = mAuthApi.setUserPic(token, pic, ext);
try {
Response<AuthResponse> response = request.execute();
AuthResponse result = response.body();
Log.i("tag", result.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
So what am I doing wrong?

Categories

Resources