I can't upload image to server it send multiple request to server and server is damp
this is my code
#Multipart
#POST("userImage")
Call<ResponseBody> sendUserFeedback(#Header("SessionID") String authorization, #Part MultipartBody.Part file, #Part("uploadfile") RequestBody name);
}
selectedImageURI = data.getData();
File file = new File(selectedImageURI.getPath());
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
fileToUpload = MultipartBody.Part.createFormData("uploadfile", file.getName(), requestBody);
filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
private void executeSendFeedbackFormSendUserImage(String sessionID, MultipartBody.Part fileToUpload, RequestBody description){
UploadImage userClient = retrofit1.create(UploadImage.class);
Call<ResponseBody> call = userClient.sendUserFeedback(sessionID, fileToUpload, description);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(AdminEditActivity.this,"success",Toast.LENGTH_SHORT).show();
if (response.body() != null){
response.code();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(AdminEditActivity.this,"error:",Toast.LENGTH_SHORT).show();
}
});
}
How to fix it???
Related
I am trying to implement retrofit2 file upload as a multipartbody, but it seems that Android Studio can't upload php files or can't pass the files to send.
Api
#Multipart
#POST("upload_img.php")
Call<ResultModel> upload_img(#Part MultipartBody.Part file);
Main.java
MultipartBody.Part body = null;
File file = new File(img_url);
RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody fileName = RequestBody.create(MediaType.parse("text/plain"), file.getName());
MultipartBody.Part filePart = MultipartBody.Part.createFormData("uploaded_file", file.getName(), fileReqBody);
Call<ResultModel> call2 = userApi.upload_img(filePart);
call2.enqueue(new Callback<ResultModel>() {
#Override
public void onResponse(Call<ResultModel> call, Response<ResultModel> response){
}
#Override
public void onFailure(Call<ResultModel> call, Throwable t) {
}
});
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 am facing problem when sending file through retrofit2. But the web api working fine on Postman hit. Error Stated in responsebody:
Response{protocol=http/1.1, code=404, message=Not Found, url=MYURL}
Retrofit2 endpoint:
#Multipart
#POST("FileStorage/UploadDataFile")
Call<ResponseBody> uploadFile(#Part MultipartBody.Part file,#Part("file") RequestBody name);
Updated code:
// Uploading File
private void uploadFile() {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
File.separator + "dbBackup"+
File.separator +"gps_db_4522_190122114644.sqlite");
//File file = new File(mediaPath);
Retrofit retrofit = RetrofitSingleton.getInstance(getActivity().getBaseContext());
final CommonApiInterface commonApiInterface = retrofit.create(CommonApiInterface.class);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
commonApiInterface.uploadFile(fileToUpload,filename).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()) {
Toast.makeText(getActivity(), "Saved Successfully...", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "Save Fail: " + t, Toast.LENGTH_SHORT).show();
}
});
}
Finally i found my problem. The endpoint was incorrect
#Multipart
#POST("FileStorage/UploadDataFile")
Call<ResponseBody> uploadFile(#Part MultipartBody.Part file,#Part("file") RequestBody name);
correct endpoint is #POST("FileProcessing/UploadDataFile")
I have looked through many stackoverflow answers but could not upload image. It used to give me Internal Server Error. Now I found a solution but it sends a null image to the server. Could you please show me where I am doing wrong.
Here is my Request CODE:
#Multipart
#POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(#PartMap Map<String, RequestBody> map);
And my CALL:
Map<String, RequestBody> map = new HashMap<>();
map.put("usermail", toRequestBody("mohammad_sed"));
map.put("content", toRequestBody(content));
map.put("islost", toRequestBody(String.valueOf(isLost)));
map.put("wasfound", toRequestBody(foundPlace));
map.put("tofind", toRequestBody(toFindPlace));
File file = new File(destination);
RequestBody reqFile = RequestBody.create(MediaType.parse("image"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
map.put("img", body);
ForumService client = Utils.getBuilder().create(ForumService.class);
Call<ResponseBody> call = client.uploadLostAndFound(map);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
mProgressDialog.dismiss();
// Toast.makeText(getApplicationContext(), "Request created", Toast.LENGTH_SHORT).show();
} else {
mProgressDialog.dismiss();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Failed to upload!", Toast.LENGTH_SHORT).show();
}
});
// This method converts String to RequestBody
public static RequestBody toRequestBody(String value) {
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
return body;
}
I tried:
#Multipart
#POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(#Part MultipartBody.Part photo,
#PartMap Map<String, RequestBody> map);
But this way I get Internal server error.
Thanks in advance.
I found the solution. I tried from postman and it was working fine.
The solution is that I had to use:
#Multipart
#POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(#Part MultipartBody.Part photo,
#PartMap Map<String, RequestBody> map);
and:
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("img", file.getName(), reqFile);
The change is I had to use "img" instead of "upload". That is a stupid mistake :D
I want to upload zip file on myserver. I am using Retrofit2. I have used the following code.
private void uploadFile() {
// create upload service client
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);
File file = uploadFile;
RequestBody requestFile =
RequestBody.create(
MediaType.parse("application/x-www-form-‌urlencoded"),
file
);
MultipartBody.Part body =
MultipartBody.Part.createFormData("fileUpload", file.getName(), requestFile);
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
Call<JSONObject> call = service.upload(description, body);
call.enqueue(new Callback<JSONObject>() {
#Override
public void onResponse(Call<JSONObject> call,
Response<JSONObject> response) {
System.out.println("UploadFragment.onResponse " + response);
Log.v("Upload", "success");
}
#Override
public void onFailure(Call<JSONObject> call, Throwable t) {
Log.d("Upload error:", t.getCause().toString());
}
});
}
My upload service is like.
public interface FileUploadService {
#Multipart
#POST("myurl")
Call<JSONObject> upload(
#Part("description") RequestBody description,
#Part MultipartBody.Part file
);
}
Problem When I upload file I get response {protocol=http/1.1, code=200, message=OK, url=http://myUrl.
It is not the response returned by my server. How can get my server response?
Its retrofit response. You will get your response in body.
response.body().toString();
Use this
System.out.println("UploadFragment.onResponse " + response.body().toString());
I hope this will help you.