Reputation: 4305
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.
Upvotes: 2
Views: 1172
Reputation: 4305
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.
Upvotes: 3