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) {
}
});
Related
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 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???
I have a fragment where, I click on Browse Button and open file manager and select the file and send it to server via POST Retrofit2.
I get the success message 200. The file is listed in server but it wont open. The size is 1kb. So, I think the file is not properly uploaded.
Following is my code.
Where am I going wrong?
File origFile = new File(PathHolder);
String getDirPath = origFile.getParent();
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), getDirPath);
multipartBody = MultipartBody.Part.createFormData("uploadFiles",origFile.getName(),requestFile);
new UploadFileAsyncTask().execute();
And the async task is
protected notificationVO doInBackground(Void... params) {
notificationVO res;
WebserviceImpl webservices = new WebserviceImpl();
res = webservices.notifyAttachment(token,multipartBody, getContext());
Log.e("File","browse uploaded");
return res;
}
Api
#Multipart
#POST("upload")
public Call<notificationVO>notifyAttachment(#Query("token")String token,
#Part MultipartBody.Part attachFile); // #Part MultipartBody.Part file
Implementation
public notificationVO notifyAttachment(String token,MultipartBody.Part fileUri,final Context context){
WebservicesApi mRestAPIWService = ApiUtilsForWS.getAPIService(context,);
Call<notificationVO> call = mRestAPIWService.notifyAttachment(token,fileUri);
try {
Response<notificationVO> response = call.execute();
if(response.isSuccessful())
{
Log.e(TAG,"Success."+response.code());
return response.body();
}
else
{
Log.e(TAG,"Failed."+response.code());
return null;
}
} catch (IOException e1) {
e1.printStackTrace();
return null;
}
}
Use interface like this below, remove #Query annotation add as #Part in your interface.
interface Service {
#Multipart
#POST("upload")
Call<notificationVO> postImage(#Part MultipartBody.Part image, #Part("token") RequestBody name);
}
Check your File path is valid and also check the file size to confirm that you are getting file properly from your file picker.
File origFile = new File(PathHolder);
int file_size = Integer.parseInt(String.valueOf(origFile .length()/1024));
If everything is OK then try this below option to upload your file it will work
RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), mFile);
RequestBody token = RequestBody.create(MediaType.parse("text/plain"), file.getName());
// Service is interface name you can use your own interface name
Service uploadImage = retrofit.create(Service.class);
Call<notificationVO> fileUpload = uploadImage.postImage(fileToUpload, token);
fileUpload.enqueue(new Callback<notificationVO>() {
#Override
public void onResponse(Call<notificationVO> call, Response<notificationVO> response) {
}
#Override
public void onFailure(Call<notificationVO> call, Throwable t) {
}
});
Interface:
#Multipart
#POST("emp/passportupload")
Single<ApiResponse> uploadPassportImage(#Query("passportnumber") String passportNumber, #Part MultipartBody.Part file);
Calling api:
File file = new File(model.getImage().getPath());
if (!file.exists()) return null;
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData(ApiConstant.PICTURE_UPLOAD_PARAM, file.getName(), requestBody);
dataService.uploadPassportImage(map, filePart)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
I am using this method to upload image to the server but server can't validate it as an image, hence giving me a response like
"Provided File Is Not A Valid Picture. Please Provide A PNG/JPG File"
But, I have uploaded the same image file through postman and it was successful. Here is the request: (N.B: passportnumber is a params, not a form data)
#Multipart
#POST("changeCompanyLogo")
Call<ChangeLogoResponse> changeCompanyLogo(#Part MultipartBody.Part image, #Part("JSON") RequestBody name);
In service write this code
ChangeLogoAPI service = ServiceHandler.getClient().create(ChangeLogoAPI.class);
File file = new File(intent.getStringExtra("imagePath"));
RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("companyLogo", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), new Gson().toJson(new ChangeLogoParams()));
Call<ChangeLogoResponse> call = service.changeCompanyLogo(body, name);
call.enqueue(new Callback<ChangeLogoResponse>() {
#Override
public void onResponse(Call<ChangeLogoResponse> call, Response<ChangeLogoResponse> response) {
Log.d(TAG, "response: " + response.isSuccessful());
}
#Override
public void onFailure(Call<ChangeLogoResponse> call, Throwable t) {
}
});
#POST("{path}")
Call<Void> uploadFile(#Header("Content-Type") String type, #Body RequestBody photo, #Path("path") String path);
File file = new File("YOUR_FILE_URI");
String filename = file.getName();
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
final String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
InputStream in = null;
RequestBody requestBody = null;
try {
in = new FileInputStream(file);
byte[] buf;
buf = new byte[in.available()];
while (in.read(buf) != -1);
requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), buf);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<Void> call = getResponse.uploadFile(type, requestBody , posturl);
U can try like this u need to set map parameter as a multipart look at the below example here I am passing both userId and image
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
MultipartBody.Part id = MultipartBody.Part.createFormData("userId", userId);
Call<ProfilePicUpdateResponse> call = apiService.updateProfilePic(id,fileToUpload);
use this awesome library : [Easily upload files (FTP / Multipart / Binary) in the background with progress indication notification] https://github.com/gotev/android-upload-service/wiki/Setup it will do the rest of work for you.
Hello i am working on upload image file using retrofit.
Can any one have idea how to pass in
You need pass mulitypart object in retrofit:
MultipartBody.Part carImage = null;
if (!TextUtils.isEmpty(imagePath)) {
File file = FileUtils.getFile(getContext(), imagePath);
// create RequestBody instance from file
final RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
carImage = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
}
public static MultipartBody.Part UploadImage(String filePath,String param) {
MultipartBody.Part body = null;
try {
body = MultipartBody.Part.createFormData("", "", null);
} catch (Exception e) {
e.printStackTrace();
}
//profileUpdateRequest.setWebsite(lblWebsite.getText().toString().trim());
if ((!filePath.equals(""))) {
File file = new File(filePath);
RequestBody photo = RequestBody.create(MediaType.parse("image/*"), file);
body = MultipartBody.Part.createFormData(param, file.getName(), photo);
}
return body;
}
Step::1Pass the file Path and it will return you MultiPart body
#Multipart
#POST(Endpoint.POST_URL)
Call<DecisionStepThirdResponse> uploadUserProfile(#Part("api_id") RequestBody api_id,
#Part("api_secret") RequestBody api_secret,
#Part("api_request") RequestBody api_request,
#Part("data") RequestBody data,
#Part MultipartBody.Part profile_image);
========================
Step 2: Pass the Request like this
public void uploadUserProfile(UpdateImageRequest request, MultipartBody.Part file, Callback<UpdateImageResponse> callback) {
String api_request = "uploadUserProfile";
String data = new Gson().toJson(request);
IRoidAppHelper.Log("application_form_permission", data);
json().uploadUserProfile(
RequestBody.create(MediaType.parse("text/plain"), api_id),
RequestBody.create(MediaType.parse("text/plain"), api_secret),
RequestBody.create(MediaType.parse("text/plain"), api_request),
RequestBody.create(MediaType.parse("text/plain"), data)
, file).enqueue(callback);
}
Step 3 : And Pass the Parameter in your Serviceclass
Please go through the following link.
Have time to refer this link :)
https://medium.com/#adinugroho/upload-image-from-android-app-using-retrofit-2-ae6f922b184c#.iinz6neii
Step 1: First initialize service class
public interface ImageUploadService {
#Multipart
#POST("upload")
Call<ResponseBody> upload(
#Part("description") RequestBody description,
#Part MultipartBody.Part file
);
}
Step 2: in next step use this where you want to upload image or file
private void uploadFile(Uri fileUri) {
// create upload service client
FileUploadService service =
ServiceGenerator.createService(ImageUploadService.class);
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
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
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
// finally, execute the request
Call<ResponseBody> call = service.upload(description, body);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
}
Step 3: you can use like this
uploadFile(Uri.fromFile(new File("/sdcard/cats.jpg")));
In your activity.
Last step: you need to add
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
In manifest in additon with
<uses-permission android:name="android.permission.INTERNET"/>
Refer this.
You can upload any type of file.
/* Create interface like below. */
public interface uploadWishImage {
#Multipart
#POST("upload/image")
Call<JsonObject> postImage(#Part MultipartBody.Part image, #Part("name") RequestBody name);
}
/* image upload code */
File file = new File("here your file path");
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "file");
uploadWishImage postService = RetrofitApi.makeNetworkRequestWithHeaders(AddWish.this).create(uploadWishImage.class);
Call<JsonObject> call = postService.postImage(body, name);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
// somethings to do with reponse
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
// Log error here since request failed
}
});