Not able to upload image file on server using retrofit - android

My file picked from gallery and set to imageview but after click on upload button not able upload my file on server
I am using local host,my server side code is correct because image is uploading via postman
File file = new File(mediaPath);
// parsing media type file
RequestBody requestBody1 = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("input_img", file.getName(), requestBody1);
ServiceApi call = ClientApi.getData().create(ServiceApi.class);
Call<ResponseData> data = call.update(fileToUpload1);
data.enqueue(new Callback<ResponseData>()
{
#Override
public void onResponse(Call<ResponseData> call, Response<ResponseData> response)
{
ResponseData data = response.body();
if(data.getStatus().equals("true"))
{
Toast.makeText(getApplicationContext(), "yes",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "no",Toast.LENGTH_SHORT).show();
}
// Log.d("data",data.getUpdateUserData().toString());
}
#Override
public void onFailure(Call<ResponseData> call, Throwable t)
{
Toast.makeText(getApplicationContext(), "Please check once",Toast.LENGTH_SHORT).show();
}
});

Related

Android Image Uploading on Localhost but not on online server

I am building a Laravel-based API. In the project, I want to upload image using post method to the API server
the image file is uploading on localhost database but when I try to upload the image on online server which is namecheap there image error code is 405.
I wasted 2 days but I don't now what is the error.
Please anyone can help me.
Thanks in advance
Here is android code
#Multipart
#POST("update-client")
Call<CustomerModel> update_user(#Part("id") RequestBody id,
#Part("name") RequestBody name, #Part("address") RequestBody address,
#Part("user_op_phone") RequestBody city,
#Part MultipartBody.Part file,
#Part("avatar") RequestBody image);
public void update_user_info(String name,String address,String no){
progressDialog.show();
RequestBody requestFile = null;
MultipartBody.Part body = null;
if(file!=null && file.length()>0) {
requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
body =
MultipartBody.Part.createFormData("avatar", file.getName(), requestFile);
}
RequestBody p_id = RequestBody.create(MediaType.parse("text/plain"),appSessionManager.getUserId());
RequestBody p_name = RequestBody.create(MediaType.parse("text/plain"),name);
RequestBody p_address = RequestBody.create(MediaType.parse("text/plain"),address);
RequestBody p_no = RequestBody.create(MediaType.parse("text/plain"),no);
Call<CustomerModel> call1 = apiPHP.update_user(body,requestFile);
call1.enqueue(new Callback<CustomerModel>() {
#Override
public void onResponse(Call<CustomerModel> call, Response<CustomerModel> response) {
progressDialog.dismiss();
// VendorModel user1 = response.body();
if(response.errorBody()==null){
// if(response.code()==201) {
Toast.makeText(getApplicationContext(), response.body().message, Toast.LENGTH_LONG).show();
// }
}
}
#Override
public void onFailure(Call<CustomerModel> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.getMessage() , Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
Laravel Api routes is
Route::post("update-client", "Client\ClientController#updateClient");

File upload using retrofit android?

I am trying to upload a video file using multipart by retrofit and I get the following error in response
Response{protocol=http/1.1, code=405, message=Method Not Allowed, url=serverurl/Upload/Videos/}
This is my code for file upload
void uploadVideo(String videoPath) {
dialog.show();
File videoFile = new File(videoPath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), videoPath);
MultipartBody.Part vFile = MultipartBody.Part.createFormData("file", videoFile.getName(), requestFile);
apiCall.uploadVideoToServer(presenter.getUserInfo().getUploadVideoPath(), vFile).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
dialog.dismiss();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
dialog.dismiss();
}
});
}
This is the path I am uploading the file to
http://serverurl.com/Upload/Videos/
Can someone tell me whats wrong with my code?
Retrofir API interface
#Multipart
#POST
Call<String> uploadVideoToServer(#Url String url, #Part MultipartBody.Part video);
in your api service interface :
#Multipart
#POST("Upload/Videos") // *** DONT FORGET UR END POINT HERE ***
Call<urmodel> uploadVideoToServer(#PartMap Map<String, RequestBody> map);
and write a method to upload ur video file like this :
private void uploadVideoToServer(String path) {
File videoFile = new File(path);
if (videoFile.exists()) {
//create request body
Map<String, RequestBody> map = new HashMap<>();
RequestBody requestBody = RequestBody.create(MediaType.parse("video/*"), videoFile);
map.put("video\"; filename=\"" + videoFile.getName() + "\"", requestBody);
//make call
Call<urmodel> call = mTService.uploadVideoToServer(map);
call.enqueue(new Callback<urmodel>() {
#Override
public void onResponse(Call<urmodel> call, Response<urmodel> response) {
if (response.isSuccess()) {
// DO SOMETHING
} else {
// DO SOMETHING
}
}
#Override
public void onFailure(Call<urmodel> call, Throwable t) {
//occur when fail to deserialize || no network connection || server unavailable
Toast.makeText(getBaseContext(), "Fail it >> " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(getBaseContext(), "can not upload file since the file is not exist :|", Toast.LENGTH_SHORT).show();
}
}

My ProgressDialog is Not Disappearing

I am working on a project in android to upload a file to server using file chooser But there is a problem, when i am Uploading more than 500 kB file. The file is uploaded but My Progress Dialog is not disappearing and if i uploaded file 100 KB it's uploaded to server and i got a message file uploaded successfully. But I'm not able to get server response if i uploaded more than 500 kB file. Please Help me. Thank You.
It's my UploadFile() Methods
private void uploadFile() {
dialog = ProgressDialog.show(getActivity(), "", "Uploading File...", true);
// Map is used to multipart the file using okhttp3.RequestBody
Map<String, RequestBody> map = new HashMap<>();
long maxLength = 10000000;
File file = new File(selectedFilePath);
if(file.length() > maxLength){
Toast.makeText(getActivity(), "can't upload file if size more than 10mb", Toast.LENGTH_LONG).show();
dialog.dismiss();
}else {
String name = tv_name.getText().toString();
String email = tv_email.getText().toString();
// Parsing any Media type file
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
RequestBody requestBody1 = RequestBody.create(MediaType.parse("text/plain"), name);
RequestBody requestBody2 = RequestBody.create(MediaType.parse("text/plain"), email);
map.put("file\"; filename=\"" + selectedFilePath + "\"", requestBody);
map.put("name\"; username=\"" + name + "\"", requestBody1);
map.put("email\"; email=\"" + email + "\"", requestBody2);
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<ServerResponse> call = getResponse.upload("token", map);
call.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
// Log.v("Response", serverResponse.toString());
}
dialog.dismiss();
goToProfile();
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
}
});
}
}
When you get response you have to dismiss your progress dialog.
Example:
if (cls_networlconnection.isOnline())
{
progressdialog = ProgressDialog.showdialog(this,"Loading");
APICall();
}
else {
Toast.makeText(getApplicationContext(),UserToastMessage.NETWORKCONNECTION, Toast.LENGTH_LONG).show();
callNoconnection();
}
API Call Success()
{
if(progressDialog.isShowing)
progressDialog.dismiss();
//your logic
}
Update your onFailure code :
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
dialog.dismiss();
}
Also in onResponse, first you need to dismiss dialog :
#Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
if(progressDialog.isShowing){
dialog.dismiss();
}
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
// Log.v("Response", serverResponse.toString());
}
goToProfile();
}

How to upload image using Retrofit2 and save it on NodeJS server?

I have android app that posts image to NodeJS server using Retrofit2.
Here is my Android/Java code:
public interface ApiInterface {
String ENDPOINT = "http://192.168.0.11:1337/";
#Multipart
#POST("users/avatar")
Call<Avatar> postAvatar(#Part("description") RequestBody description, #Part("image") MultipartBody.Part file);
public static final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
private void uploadAvatar(final String userid){
File file = new File("/storage/emulated/0/Android/data/com.bcg.loginexample/files/pic.jpg");
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body =MultipartBody.Part.createFormData("image", file.getName(), requestFile);
String descriptionString = "hello, this is description speaking";
RequestBody description =RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
ApiInterface mApiService = ApiInterface.retrofit.create(ApiInterface.class);
Call<Avatar> mService= mApiService.postAvatar(description, body );
mService.enqueue(new Callback<Avatar>() {
#Override
public void onResponse(Call<Avatar> call, Response<Avatar> response) {
Avatar avatar = response.body();
String returnedResponse = avatar.avatar_url;
Toast.makeText(LoginActivity.this, "Returned " + returnedResponse, Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<Avatar> call, Throwable t) {
call.cancel();
Toast.makeText(LoginActivity.this, "Please check your network connection", Toast.LENGTH_LONG).show();
}
});
}
And NodeJS
app.post('/users/avatar', type,
function (req, res) {
var filePath = __dirname + '/uploads/avatar.jpg';
fs.appendFile(filePath, req.body.image, function () {
res.end('file uploaded');
});
});
This is all I see in body object at NodeJS side.
"{"headers":{"namesAndValues":["Content-Disposition","form-data; name=\"image\"; filename=\"pic.jpg\""]}}"
Don't understand where is the image here and how to save it ??
You need some extra middleware to handle multipart/form-data (upload of binary data). You can take a look at the multer module for example.

Retrofit 2 : send files with json object

I'm sending object in request body, something like that :
{
"title":"test",
"description":"test",
"images":[]
}
#POST("create-data")
Call<JsonObject> publishData(#Body MyObject object);
and it's work fine without the images. From the docs I can find how to upload file to server using MultipartBody.Part, my questions is :
How can I upload multiple images at the same time?
Is it possible to send the images inside the object, or I need to send it separately and how ?
thank you very much.
request success just now with server
I reference the article:
https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server
#Multipart
#POST("uploadHeadPic")
Call<UploadHeadPicResponseModel> uploadHeadPic(#Part MultipartBody.Part file, #Part("json") RequestBody json);
public void doUploadHeadPic(#NonNull String filePath) {
if (!MNetworkUtil.isNetworkAvailable()) {
MToastUtil.show("网络不能连接");
return;
}
File file = new File(filePath);
String json = new Gson().toJson(new UploadHeadPicRequestModel());
if (!file.exists()) {
MToastUtil.show("文件不存在");
return;
}
progressDialog.show();
avatarSimpleDraweeView.setEnabled(false);
MApiManager.getService().uploadHeadPic(
MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)),
RequestBody.create(MediaType.parse("multipart/form-data"), json))
.enqueue(new OnRetrofitCallbackListener<UploadHeadPicResponseModel>(mActivity) {
#Override
public void onSuccess(UploadHeadPicResponseModel responseModel) {
progressDialog.dismiss();
avatarSimpleDraweeView.setEnabled(true);
if (responseModel != null) {
String serverAvatarUrl = responseModel.data.headPicPath;
if (!TextUtils.isEmpty(serverAvatarUrl)) {
UserModel userModel = MUserManager.getInstance().getUser();
if (userModel != null) {
userModel.setAvatarUrl(serverAvatarUrl);
MUserManager.getInstance().updateOrInsertUserInfo(userModel);
MToastUtil.show("上传头像成功");
}
}
}
}
#Override
public void onFailure(int status, String failureMsg) {
progressDialog.dismiss();
avatarSimpleDraweeView.setEnabled(true);
MToastUtil.show((TextUtils.isEmpty(failureMsg) ? "上传失败" : failureMsg) + " : " + status);
}
});
}
update for multi files
may be this could help , I did not try
#Multipart
#POST("uploadHeadPic")
Call<UploadHeadPicResponseModel> uploadHeadPic(#Part MultipartBody.Part file0, #Part MultipartBody.Part file1, #Part("json") RequestBody json);
public void doUploadHeadPic(#NonNull String filePath) {
MApiManager.getService().uploadHeadPic(
MultipartBody.Part.createFormData("file0", file0.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file0)),
MultipartBody.Part.createFormData("file1", file1.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file1)),
RequestBody.create(MediaType.parse("multipart/form-data"), json))
.enqueue(new OnRetrofitCallbackListener<UploadHeadPicResponseModel>(mActivity) {
#Override
public void onSuccess(UploadHeadPicResponseModel responseModel) {
}
#Override
public void onFailure(int status, String failureMsg) {
}
});
}
In my case (uploading to server built with Spring) I needed to change MediaType for RequestBody:
RequestBody.create(MediaType.parse("application/json"), json)
RequestBody.create(MediaType.parse("image/jpg"), file)

Categories

Resources