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
Related
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());
}
});
}
}
Here is how I get the image from photo library:
private void presentPhotoSelector() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null) {
mSelectedPhotoUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), mSelectedPhotoUri);
photoCircleImageView.setImageBitmap(bitmap);
photoCircleImageView.setVisibility(View.VISIBLE);
selectPhotoButton.setVisibility(View.INVISIBLE);
uploadImageToServer(mSelectedPhotoUri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is how I try to upload it:
public class JSONResponse {
boolean userUploadedProfileImage;
User user;
}
private void uploadImageToServer(Uri selectedPhotoUri) {
if (selectedPhotoUri == null) {
Log.d(TAG, "uploadImageToServer: selectedPhotoUri is null");
return;
}
if (!AuthService.getInstance(mContext).isLoggedIn()) {
Log.d(TAG, "uploadImageToServer: User not logged in");
return;
}
showLoading("Laster opp bilde...", "Vennligst vent mens prosess foregÄr");
File file = new File(selectedPhotoUri.getPath());
final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpeg");
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "image.jpg",
RequestBody.create(MEDIA_TYPE_JPG, file))
.build();
Request request = new Request.Builder()
.header("Authorization", "Bearer " + AuthService.getInstance(mContext).getToken())
.url(Config.URL + "/api/user/upload-profile-image")
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
hideLoading();
}
});
Log.d(TAG, "onFailure: response failed: " + e.getLocalizedMessage());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
hideLoading();
}
});
String responseBodyString = response.body().string();
Log.d(TAG, "onResponse: responseBodyString: " + responseBodyString);
Gson gson = new Gson();
SettingsFragment.JSONResponse jsonResponse = gson.fromJson(responseBodyString, SettingsFragment.JSONResponse.class);
if (jsonResponse != null) {
UserService.getInstance(mContext).setMyUser(jsonResponse.user);
Log.d(TAG, "onResponse: jsonResponse.userUploadedProfileImage: " + jsonResponse.userUploadedProfileImage);
Log.d(TAG, "onResponse: jsonResponse.user: " + jsonResponse.user.toString());
}
}
});
}
This does not work, the loader never stops spinning and on server side I get this error: multipart: NextPart: client disconnected
However, if I change the code above from:
File file = new File(selectedPhotoUri.getPath());
to:
String file = selectedPhotoUri.getPath();
Then request is successful, however, when I try to open the image on a browser it says "the image cannot be displayed because it contains errors". When I look at the database I can see that it interpreted its mime type as: application/octet-stream, and not image/jpeg.
I am stuck and I don't know what to do.
I am now getting this error on console: onFailure: response failed: /-1/1/content:/media/external/images/media/69/ORIGINAL/NONE/656735600 (No such file or directory)
I am running this on a simulator, if that helps.
One way is:
You have to convert Bitmap to Base64(String) and send that base64 to server.
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();
}
}
I have a function to request upload image with Retrofit like this
void uploadPhoto(File file) {
RequestBody photo = RequestBody.create(MediaType.parse("application/image"), file);
RequestBody body = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("photo", file.getName(), photo)
.build();
fragment.showProgressDialog(fragment.loading);
fragment.getApi().uploadPhoto(PrefHelper.getString(PrefKey.TOKEN), body)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<GenericResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
fragment.dismissProgressDialog();
Timber.e(e.getMessage());
}
#Override
public void onNext(GenericResponse response) {
fragment.dismissProgressDialog();
if (response.getCode() == 1) {
fragment.showSuccessDialog("Saving success", false);
userInfo();
}
}
});
}
and for the example, I have a button to upload image in my fragment
#OnClick(R.id.btnChangePicture)
void onChangePictureClicked() {
}
What code should i put in
OnChangePictureClicked
So i can choose an image from gallery and then I request it to API.
void uploadPhoto(File file)
Thanks
Transform your image to an array of bytes and then create an Object Dto like the example below and send it to the server through Retrofit.
#Data
public class SetProfileImageRequestDto {
#SerializedName("Token")
private String token;
#SerializedName("Stream")
private byte[] image;
}
Retrofit Api Service:
#POST("SetProfileImage/")
Observable<ResultResponseDto> setProfileImage(#Body SetProfileImageRequestDto profileImageRequestDto);
Hope it works.
Create a Uri object in Activity or fragment.
private Uri selectedImage;
After that, You will get gallery result in onActivityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
selectedImage = data.getData();
}
}
Then in your onChangePictureClicked method.
#OnClick(R.id.btnChangePicture)
void onChangePictureClicked() {
if(selectedImage !=null){
uploadPhoto(new File(selectedImage.getPath()));
}
}
You can use multipart with retrofit please look this example of image upload using retrofit, its best for you.
its working for me.
//Create Upload Server Client
ApiService service = RetroClient.getApiService();
//File creating from selected URL
File file = new File(imagePath);
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body =
MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile);
Call<Result> resultCall = service.uploadImage(body);
resultCall.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
progressDialog.dismiss();
// Response Success or Fail
if (response.isSuccessful()) {
if (response.body().getResult().equals("success"))
Snackbar.make(parentView, R.string.string_upload_success, Snackbar.LENGTH_LONG).show();
else
Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show();
}
/**
* Update Views
*/
imagePath = "";
textView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
progressDialog.dismiss();
}
});
http://www.pratikbutani.com/2016/06/android-upload-image-file-using-retrofit-2-0/
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();
}
}
}