How to Post image and data in android retrofit - android

I am unable to post data and image using retrofit. can u please help me
#Multipart
#POST("click_and_post")
Call<ResponseBody> clicPost(
#Part ("click_and_post[image]") RequestBody file,
#Part ("click_and_post[category_id]") String category_id,
#Part ("click_and_post[brand_id]") String brand_id,
#Part ("click_and_post[location]") String location);
POst man
I am unable to send data can u help me

This is how you should implement this api
int size = youImagePathList.size();
MultipartBody.Part[] multipartImageList = new MultipartBody.Part[size];
if(size > 0) {
for (int i = 0; i < size; i++) {
File file = new File(notificationItemList.get(i).getImageEncoded());
RequestBody surveyBody = RequestBody.create(MediaType.parse("image/*"), file);
multipartImageList[i] = MultipartBody.Part.createFormData(""click_and_post[image]"", file.getName(), surveyBody);
}
}
RequestBody category_id = RequestBody.create(MediaType.parse("multipart/form-data"), StringCategoryID);
RequestBody brand_id = RequestBody.create(MediaType.parse("multipart/form-data"), StringBrandId);
RequestBody location = RequestBody.create(MediaType.parse("multipart/form-data"), StringLocation);
#Multipart
#POST("click_and_post")
Call<ResponseBody> clicPost(
#Header("Authorization") String authorization, // if there is headers
#Part MultipartBody.Part[] multipartImageList,
#Part("click_and_post[category_id]") RequestBody category_id,
#Part("click_and_post[brand_id]") RequestBody brand_id,
#Part("click_and_post[location]") RequestBody location);

Related

Why can't I upload an image and data with retrofit2?

Regards, I have to upload this data.
postman
And I have this code.
Customer Creation
public BeeMappingClient(String url){
retrofit= new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
conexion=retrofit.create(Conexion.class);
}
Interface
#Multipart
#POST("task")
Call<ResponsetTask> API_Task(#Header("Authorization") String key,
#Part MultipartBody.Part multipartImage,
#Part("message") RequestBody message ,
#Part("filecomment") RequestBody filecomment,
#Part("api_token") RequestBody api_token,
#Part("user_id") RequestBody user_id);
And call
File file=new File(path);
MultipartBody.Part[] multipartImageList = new MultipartBody.Part[1];
RequestBody surveyBody = RequestBody.create(MediaType.parse("image/*"), file);
multipartImageList[0] = MultipartBody.Part.createFormData("image", "image.jpg", surveyBody);
RequestBody message = RequestBody.create(MediaType.parse("message"), Constantes.MESSAGE);
RequestBody filecomment = RequestBody.create(MediaType.parse("filecomment"), Constantes.FILECOMMENT);
RequestBody api_token = RequestBody.create(MediaType.parse("api_token"),Constantes.api_token);
RequestBody user_id = RequestBody.create(MediaType.parse("user_id"), Integer.toString(Constantes.id));
Call<ResponsetTask> call = conexion.API_Task(Constantes.AUTH,multipartImageList[0],message,filecomment,api_token,user_id);
call.enqueue(new Callback<ResponsetTask>() {
#Override
public void onResponse(Call<ResponsetTask> call, Response<ResponsetTask> response) {
Constantes.api_task=response.body().getTaskId();
}
#Override
public void onFailure(Call<ResponsetTask> call, Throwable t) {
}
});
The problem is that it does nothing, if I do a debug all seems to be going well until it reaches the call.enqueu ... there I should enter OnResques or OnFailure but it does not just go to the end of the method as if it did not exist .
What should I do ?, this is the best method to upload this data ?.
I thank you in advance for any help or guidance you can give me.
Try this - for multipart request
In interface
#Multipart
#POST("task")
Call<ResponseBody> submitRegistration(#Part MultipartBody.Part body,
#Part("message") RequestBody message)
Pass values -
File file = new File(path);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
RequestBody message = RequestBody.create(MediaType.parse("text/plain"), Constantes.MESSAGE);
Call -
Call<ResponseBody> call = service.callApi(body,message);
RequestBody surveyBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
Replace "image/*" with "multipart/form-data"

Is it possible to send #Fields with multipart in retrofit2?

I'm using retrofit2, i was sending data through it using #FormUrlEncoded because everything was as a string even images but i faced some errors when i send collection of images as strings, so i changes to multipart.
Now i'm facing problem that i can't send #Field of string with multipart.
So, how i can solve this problem without using RequestBody for every string?
here's my code
#Multipart
#POST("/androidfiles/insertNews.php")
Call<ResponseBody> uploadImage(#Part MultipartBody.Part file, #Part("name") RequestBody name,
#Field("tArabic") String arabicTitle,
#Field("tEnglish") String englishTitle,
#Field("tRussian") String russianTitle,
#Field("tItalian") String italianTitle,
#Field("dArabic") String arabicDescription,
#Field("dEnglish") String englishDescription,
#Field("dRussian") String russianDescription,
#Field("dItalian") String italianDescription);
and here.
private void insertNews(Uri uri){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ServiceConstants.URL)
.build();
File file = FileUtil.getFile(this, uri);
RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), mFile);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
ApiConfig apiConfig = retrofit.create(ApiConfig.class);
Call<ResponseBody> addNews = apiConfig.uploadImage(fileToUpload,
filename,
etArabicTitle.getText().toString(),
etEnglishTitle.getText().toString(),
etRussianTitle.getText().toString(),
etItalianTitle.getText().toString(),
etArabicDescription.getText().toString(),
etEnglishDescription.getText().toString(),
etRussianDescription.getText().toString(),
etItalianDescription.getText().toString());
addNews.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(News.this, "success" + "\n" + response.message(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(News.this,Menu.class);
startActivity(intent);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(News.this, "fail" + t.getMessage(), Toast.LENGTH_SHORT).show();
t.printStackTrace();
}
});
}
When using multipart requests using Retrofit, you can pass extra parameters using #Part annotation having RequestBody fields for additional parameters.
So, You can pass it as RequestBody type for all parameters except multipart body like below :
#Multipart
#POST("/androidfiles/insertNews.php")
Call<ResponseBody> uploadImage(#Part MultipartBody.Part file,
#Part("name") RequestBody name,
#Part("tArabic") RequestBody arabicTitle,
#Part("tEnglish") RequestBody englishTitle,
#Part("tRussian") RequestBody russianTitle,
#Part("tItalian") RequestBody italianTitle,
#Part("dArabic") RequestBody arabicDescription,
#Part("dEnglish") RequestBody englishDescription,
#Part("dRussian") RequestBody russianDescription,
#Part("dItalian") RequestBody italianDescription);
Now, for calling such API; you'll need to pass it by creating RequestBody for additional parameters as MIME Type text/plain using syntax (i.e. RequestBody.create(MediaType.parse("text/plain"), your variable goes here))
During API build up, you can pass call it as:
Call<ResponseBody> addNews = apiConfig.uploadImage(fileToUpload,
filename,
RequestBody.create(MediaType.parse("text/plain"), etArabicTitle.getText().toString()), //This will make it as RequestBody to pass it along image/files.
RequestBody.create(MediaType.parse("text/plain"), etEnglishTitle.getText().toString()),
RequestBody.create(MediaType.parse("text/plain"), etRussianTitle.getText().toString()),
RequestBody.create(MediaType.parse("text/plain"), etItalianTitle.getText().toString()),
RequestBody.create(MediaType.parse("text/plain"), etArabicDescription.getText().toString()),
RequestBody.create(MediaType.parse("text/plain"), etEnglishDescription.getText().toString()),
RequestBody.create(MediaType.parse("text/plain"), etRussianDescription.getText().toString()),
RequestBody.create(MediaType.parse("text/plain"), etItalianDescription.getText().toString()));
try changing #Field to #Part . like this :
#Multipart
#POST("/androidfiles/insertNews.php")
Call<ResponseBody> uploadImage(#Part MultipartBody.Part file, #Part("name") RequestBody name,
#Part("tArabic") String arabicTitle,
#Part("tEnglish") String englishTitle,
#Part("tRussian") String russianTitle,
#Part("tItalian") String italianTitle,
#Part("dArabic") String arabicDescription,
#Part("dEnglish") String englishDescription,
#Part("dRussian") String russianDescription,
#Part("dItalian") String italianDescription);

Multiple image uploading using multipart retrofit or volley

Hi Can any one Please help me out in uploading multiple images selected from gallery,
parameter is 'images' as array list
I have tried with this but no response can any one help me out..
This is my request body :
MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
MultipartBody.Builder mRequestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
if (Imagepaths.size() > 0) {
for(String path:Imagepaths) {
File file = new File(path);
mediaType = path.endsWith("png") ?
MediaType.parse("image/png") : MediaType.parse("image/jpeg");
RequestBody imageBody = RequestBody.create(mediaType, file);
mRequestBody.addFormDataPart("images", file.getName(), imageBody);
}
}
RequestBody rb = mRequestBody.build();
This is the retrofit call :
#Multipart
#POST("upload_images/")
Call<ResponseBody> retrofitImageUpload(#Header("Authorization") String auth,
#Header("Content-Type") String contentType,
#Part("images") RequestBody req);

upload array of images in multipart retrofit2

I need to upload an array of images on server using multi-part.and I Also want to give key to that array, otherwise server don't recognize the array. I have tried the solutions below, but these do not work:
Solution1 :
MultipartBody.Part[] array = new MultipartBody.Part[items.size()];
for(int i=0;i<items.size();i++){
File file = new File(items.get(i));
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("value_"
+ String.valueOf(uploadMissionRequestModel.getStepId()), file.getName(),
requestBody);
array[i]=filePart;
}
RequestBody apiKey = RequestBody.create(MediaType.parse("text/plain"),
uploadMissionRequestModel.getApiKey());
RequestBody stepId = RequestBody.create(MediaType.parse("text/plain"),
String.valueOf(uploadMissionRequestModel.getStepId()));
RequestBody missionId = RequestBody.create(MediaType.parse("text/plain"),
String.valueOf(uploadMissionRequestModel.getMissionId()));
RequestBody overWrite = RequestBody.create(MediaType.parse("text/plain"),
"yes");
Map<String, RequestBody> partMap = new HashMap<>();
partMap.put("api_token", apiKey);
partMap.put("MissionID", missionId);
partMap.put("overwrite", overWrite);
partMap.put("StepID", stepId);
ApiServices service = RestClient.getClient();
final Call<UploadMissionResponse> call = service.uploadFiles(partMap, array);
Solution2
RequestBody[] image_id = new RequestBody[items.size()];
for(int i=0;i<items.size();i++){
File file = new File(items.get(i));
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
image_id[i]=requestBody;
}
RequestBody apiKey = RequestBody.create(MediaType.parse("text/plain"),
uploadMissionRequestModel.getApiKey());
RequestBody stepId = RequestBody.create(MediaType.parse("text/plain"),
String.valueOf(uploadMissionRequestModel.getStepId()));
RequestBody missionId = RequestBody.create(MediaType.parse("text/plain"),
String.valueOf(uploadMissionRequestModel.getMissionId()));
RequestBody overWrite = RequestBody.create(MediaType.parse("text/plain"),
"yes");
Map<String, RequestBody> partMap = new HashMap<>();
partMap.put("api_token", apiKey);
partMap.put("MissionID", missionId);
partMap.put("overwrite", overWrite);
partMap.put("StepID", stepId);
Map<String, RequestBody[]> imageMap = new HashMap<>();
imageMap.put("value_8",image_id);
ApiServices service = RestClient.getClient();
final Call<UploadMissionResponse> call = service.uploadFiles(partMap, imageMap);
Please suggest, How I can pass array of images with key name using retrofit2.
My request method:
#Multipart
#POST("admin/assets/upload/")
Observable<UploadResponse> uploadFiles(#Part MultipartBody.Part... files);
Creating parts from array of uri's. All parts will have key 'files[]', the one my backend recognizes:
//UriHandle and OkioUtil are my own classes to handle both 'content' and 'file' uris
//files has type of Uri[]
final MultipartBody.Part[] parts = new MultipartBody.Part[files.length];
for (int i = 0; i < files.length; i++) {
final UriHandle handle = UriUtil.getUriHandle(context, files[i]);
final RequestBody body = OkioUtil.create(handle, mediaType);
parts[i] = MultipartBody.Part.createFormData("files[]", handle.name(), body);
}
Sending request:
api.uploadFiles(part)
.subscribeOn(...)
.observeOn(...)
.subscribe(result -> ...);
if I were you I would convert images to Base64 and send List<String> for images using your second solution.

Android Retrofit 2 multipart always giving error 400

I'm trying to send one image and somes string through retrofit, but it's not working, I'm always getting a 400. My app is already using webservices such as GET or POST without troubles, I assume that my probleme is with the upload...
I used that explanations and the github of retrofit.
My idea here is to create a new Dish and sed it to my server, so most of the data are comming from InputTextField and the photo is taken by the camera using an Intent
First my interface for uploading
#Multipart
#POST("japronto/api/chef/dish/new")
Call<Dish> upload(#Part("name") RequestBody name, #Part("description") RequestBody description,#Part("disponibility") RequestBody disp,#Part("max") RequestBody max,#Part("price") RequestBody price, #Part MultipartBody.Part file);
My function to upload
public void onOK(){
RequestBody name = RequestBody.create( MediaType.parse("multipart/form-data"), this.name.getText().toString());
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), this.description.getText().toString());
RequestBody disp =
RequestBody.create(
MediaType.parse("multipart/form-data"), Integer.toString(this.TorF));
RequestBody max =
RequestBody.create(
MediaType.parse("multipart/form-data"), this.max.getText().toString());
RequestBody price =
RequestBody.create(
MediaType.parse("multipart/form-data"), this.price.getText().toString());
File nImg = new File(folderImg, imgName);
RequestBody rqFile =
RequestBody.create(MediaType.parse("multipart/form-data"), nImg);
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", nImg.getName(), rqFile);
ApiService apiService = ApiManager.createService(ApiService.class, this.chef.getPseudo(), this.chef.getPassword());
Call<Dish> call = apiService.upload(name, description, disp, max, price, body);
call.enqueue(new Callback<Dish>() {
#Override
public void onResponse(Call<Dish> call, Response<Dish> response) {
Dish d = response.body();
Log.d(TAG, "onResponse: "+d.getName());
}
#Override
public void onFailure(Call<Dish> call, Throwable t) {
}
});
}
My view on the server
#app.route('/japronto/api/chef/dish/new', methods=['POST'])
def upload():
if request.method == 'POST':
if 'file' not in request.files:
print 'pbs'
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
print filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return {'name':filename}
return{'name':'erro'}
Any ideas?
Try this
#Multipart
#POST("japronto/api/chef/dish/new")
Call<Dish> upload(#Part("name") RequestBody name, #Part("description") RequestBody description,#Part("disponibility") RequestBody disp,#Part("max") RequestBody max,#Part("price") RequestBody price, #Part("ImageNameHere\"; filename=\"image.png\" ") RequestBody image);
File nImg = new File(folderImg, imgName);
RequestBody rqFile = RequestBody.create(MediaType.parse("image/png"), nImg);
check these links
Link 1 Link 2 Link 3

Categories

Resources