Upload file in Retrofit 2 - android

I tried the following but on response i am getting 500 error (Internal Server Error) -- help me design the interface for the request in the above screenshot...thanks
#Multipart
#POST("myrecord")
Call<ResponseBody> addRecord(#Query("token") String token,#Query("userid") int userId,
#Query("name") String name, #Part("file") RequestBody file);
File file = new File(getRealPathFromURI(data.getData()));
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), getRealPathFromURI(data.getData()));`
Call<ResponseBody> responseBodyCall = service.addRecord(token, userId,
"newFileName", requestFile);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("Response", "="+response.code());
Log.d("Response", "= "+response.message());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("failure", "message = " + t.getMessage());
Log.d("failure", "cause = " + t.getCause());
}
});`

The following code worked :)
#Multipart
#POST("myrecord")
Call<ResponseBody> addRecord(#Query("token") String token, #Query("userid") int userId,
#Query("name") String name, #Part MultipartBody.Part file);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == FILE_SELECT_CODE) && (resultCode == -1)) {
File file = new File(getRealPathFromURI(data.getData()));
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), getRealPathFromURI(data.getData()));
MultipartBody.Part multipartBody =MultipartBody.Part.createFormData("file",file.getName(),requestFile);
Call<ResponseBody> responseBodyCall = service.addRecord(token, userId, "fileName", multipartBody);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("Success", "success "+response.code());
Log.d("Success", "success "+response.message());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("failure", "message = " + t.getMessage());
Log.d("failure", "cause = " + t.getCause());
}
});
}
}

#Multipart
#POST("myrecord")
Call<ResponseBody> addRecord(#Part("file") RequestBody file,#Part MultipartBody.Part file,
#Query("token") String token,#Query("userid") int userId,#Query("name") String name);
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
String descriptionString = "your description";
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), descriptionString);
for more information look into this link:
https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server

If you would like to send file as binary in a body without using multipart you can remove #Multipart annotation from your code and use #Body annotation. It looks like
#POST("myrecord")
Call<ResponseBody> addRecord(#Query("token") String token,#Query("userid") int userId,
#Query("name") String name, #Body RequestBody file);
File file = new File(getRealPathFromURI(data.getData()));
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), getRealPathFromURI(data.getData()));
Call<ResponseBody> responseBodyCall = service.addRecord(token, userId,
"newFileName", requestFile);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("Response", "="+response.code());
Log.d("Response", "= "+response.message());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("failure", "message = " + t.getMessage());
Log.d("failure", "cause = " + t.getCause());
}
});`

public String getRealPathFromURI(Context context, Uri contentUri) {
Log.d("imin", "onClick: in image conversion");
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
Log.d("imin", "onClick: in image conversion try");
return cursor.getString(column_index);
} finally {
Log.d("imin", "onClick: in image conversion finally");
if (cursor != null) {
cursor.close();
}
}
}

Related

How to send aes encrypted Multipart Entity file and parameters with Retrofit to the server?

How to send aes encrypted Multipart Entity file and parameters with Retrofit to the server in Android?
#Multipart
#POST("yourapi")
Call<ResponseBody> addRecord(#Part MultipartBody.Part file);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == FILE_SELECT_CODE) && (resultCode == -1)) {
File file = new File(getRealPathFromURI(data.getData()));
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), getRealPathFromURI(data.getData()));
MultipartBody.Part multipartBody =MultipartBody.Part.createFormData("file",file.getName(),requestFile);
Call<ResponseBody> responseBodyCall = service.addRecord( multipartBody);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("Success", "success "+response.code());
Log.d("Success", "success "+response.message());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("failure", "message = " + t.getMessage());
Log.d("failure", "cause = " + t.getCause());
}
});
}
}

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();
}
}

Bad request while sending multpart image through retrofit 2.1.0

private void saveImageToServer(final String savedpath) {
showLoader();
NetworkUtil.checkInternetConnection(DetailActiveSRActivity.this, new NetworkUtil.NetworkStatusListener() {
#Override
public void onNetworkAvailable() {
File file = new File(savedpath);
// RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), savedpath);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
Log.e(TAG, "onNetworkAvailable: requestFIle " + savedpath+"\n"+" file "+file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Log.e(TAG, "onNetworkAvailable: body " + body);
RequestBody reqUserId = RequestBody.create(MediaType.parse("text/plain"), userId);
//RequestBody reqImageType =RequestBody.create(MediaType.parse("text/plain"), "1");
Call<SaveImageResponseModel> responseCall = mService.saveImages(body, reqUserId);
responseCall.enqueue(new Callback<SaveImageResponseModel>() {
#Override
public void onResponse(Call<SaveImageResponseModel> call, retrofit2.Response<SaveImageResponseModel> response) {
hideLoader();
if (response != null) {
SaveImageResponseModel apiResponse = response.body();
if (apiResponse != null && apiResponse.getStatus()) {
Log.e(TAG, "onRequestSuccess: " + apiResponse);
} else {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noDataError), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noDataError), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<SaveImageResponseModel> call, Throwable t) {
hideLoader();
}
});
}
#Override
public void onNetworkNotAvailable() {
Toast.makeText(DetailActiveSRActivity.this, getString(R.string.noNetworkMessage), Toast.LENGTH_SHORT).show();
hideLoader();
}
});
}
#Headers({
"authkey: ABCD#123"
})
#Multipart
#POST(UrlUtils.POST_IMAGES)
Call<SaveImageResponseModel> saveImages(#Part MultipartBody.Part file, #Part("userId") RequestBody userId);
First of all, no description, please add a little bit more.
Second:
show what is the content of mService.saveImages(body, reqUserId);
is the HTTP call of POST type?
is the endpoint really working? You should for example try to make call through Postman and you'll see, if it is going through

Spring upload file using retrofit 2.1.0

I'm using spring for a backend and retrofit for rest client.
I want to upload a file
backend code
#PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(#RequestParam("file") MultipartFile file, Model model) {
String name = null;
try {
storageService.store(file);
model.addAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
files.add(file.getOriginalFilename());
name = files.get(files.size()-1).toString();
System.err.println(name.toString());
} catch (Exception e) {
model.addAttribute("message", "FAIL to upload " + file.getOriginalFilename() + "!");
}
return new ResponseEntity<String>(file.getOriginalFilename() , HttpStatus.OK);
}
function store
public void store(MultipartFile file) {
try {
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (Exception e) {
throw new RuntimeException("FAIL!");
}
}
android code to select and upload file
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = ImagePicker.getImageFromResult(getActivity(), requestCode, resultCode, data);
if (bitmap != null) {
image.setImageBitmap(bitmap);
selection=data.getData();
String[] filepath={MediaStore.Images.Media.DATA};
Cursor cursor=getActivity().getContentResolver().query(selection,filepath,null,null,null);
cursor.moveToFirst();
int column=cursor.getColumnIndex(filepath[0]);
String path=cursor.getString(column);
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);
upload(body);
}
upload function
public void upload(MultipartBody.Part path){
Call<ResponseBody> callUploader = iBackEndService.uploadAttachment(path);
callUploader.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG,"UPLODER REUSSI" +" "+response.message());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable throwable) {
Log.e(TAG,throwable.getMessage());
}
});
}
Retrofit mapping (I'm using Retrofit 2.1.0)
#Multipart
#POST("upload")
Call<ResponseBody> uploadAttachment(#Part MultipartBody.Part filePart);
my upload function jump to onResponse but the file was not upload

Retrofit2 uploading an image

I am trying to get my Retrofit2 to upload an image to my Flask server, I am not sure why it is not sending the parameter "file" when sending the request.
APIInteface.java
#Multipart
#PUT("api/user/update/")
Call<ResponseBody> UpdateUser(#QueryMap Map<String,String> options,
#Part MultipartBody.Part image, #Part("file") RequestBody file);
MainActivity:
File file = new File(filePath);
Log.d(TAG,"Calling update function");
update(file);
}
}
public void update(File file) {
Log.d(TAG,"I got called, yey!");
ApiInterface apiService = ApiClient.GetAuthClient(token).create(ApiInterface.class);
RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("multipart/form-data"), "upload_test");
data.put("uname",username.getText().toString());
data.put("fname",firstname.getText().toString());
data.put("lname",lastname.getText().toString());
data.put("address",address.getText().toString());
data.put("password",password.getText().toString());
data.put("preferance1",String.valueOf(spinner1.getSelectedItem()));
data.put("preferance2",String.valueOf(spinner2.getSelectedItem()));
data.put("preferance3",String.valueOf(spinner3.getSelectedItem()));
Call<ResponseBody> call = apiService.UpdateUser(data,body,name);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}

Categories

Resources