I am trying to send multiple files(images) in gmail but i am not able to send it. I have tried putting the multipart in array but instead of going files in a single mail, two mails are being delivered. My code is as below:
Interface:
public interface EmailService {
#Multipart
#POST("/send/email")
Call<OnlineAushadiModel> sendEmailOnlineAushadi(
#Part("FROM") RequestBody requestFrom,
#Part("TO") RequestBody requestTo,
#Part("SUBJECT") RequestBody requestSubject,
#Part("MailContain") RequestBody requestMailContain,
#Part("FileName") RequestBody requestFileName,
}
The main Activity:
private void sendData(HashMap<Integer, String> buttons) {
Date today = Calendar.getInstance().getTime();
to = RequestBody.create(MediaType.parse("text/plain"), "to");
from = RequestBody.create(MediaType.parse("text/plain"), "bajracharyasudeep#gmail.com");
subject = RequestBody.create(MediaType.parse("text/plain"), "You have received a new Order.");
content = RequestBody.create(MediaType.parse("text/plain"),
"Name: " + HomeActivity.username + "\n" +
"Contact Number: " + HomeActivity.phoneNumber + "\n" +
"Order date and Time: " + today + "\n" +
"Address For Delivery: " + etDeliveryAddress.getText().toString());
fileName = RequestBody.create(MediaType.parse("text/plain"),"hello");
fileToUpload = new MultipartBody.Part[buttons.size()];
for(int i = 0; i<buttons.size();i++){
Log.e("btnValue", buttons.get(i) + "");
File file = new File(buttons.get(i));
RequestBody mFile = RequestBody.create(MediaType.parse("image/" + fileExtension), file);
fileToUpload[i] = MultipartBody.Part.createFormData("file", file.getName(), mFile);
emailService = ApiClient.getApiClientOnlineAushadi().create(EmailService.class);
Call<OnlineAushadiModel> fileUpload = (Call<OnlineAushadiModel>) emailService.sendEmailOnlineAushadi(to,from,subject,content,fileName,fileToUpload[i]);
fileUpload.enqueue(new Callback<OnlineAushadiModel>() {
#Override
public void onResponse(Call<OnlineAushadiModel> call, Response<OnlineAushadiModel> response) {
Toast.makeText(getActivity(), "Success " + response.message(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<OnlineAushadiModel> call, Throwable t) {
Log.e("error",t.getMessage() + "");
}
});
}
I have tried other methods such as putting the api call out of the loop but it still didnot helped. Can anybody please help me to send multiple files in Multipart?
You should not upload the file in the loop. Like the code example!
private void CallAPI() {
boolean HaveFile;
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Uploading...");
pd.setCancelable(false);
pd.show();
ArrayList<MultipartBody.Part> body = new ArrayList<>();
//image path is a string list of seleted files path
if (imagePath.size() != 0) {
for (int i = 0; i < imagePath.size(); i++) {
//creating a file
File file = new File(imagePath.get(i));
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
body.add(MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile));
}
HaveFile=true;
} else {
RequestBody attachmentEmpty = RequestBody.create(MediaType.parse(/*"multipart/form-data"*/"text/plain"), "");
body.add( MultipartBody.Part.createFormData(/*"uploaded_file"*/"attachment", "0736E389-EF21-4286-BEBF-14CCD48B04A6", attachmentEmpty));
HaveFile=false;
}
APIService service =
ServiceGenerator.getclient().create(APIService.class);
Call<String> call = service.uploadMulFiles(body.size() == 0 ? null : body ,to,from,subject,content,fileName);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(#Nullable Call<String> call,
#Nullable Response<String> response) {
if (response != null) {
if (response.isSuccessful()) {
MainActivity.ComObj.ShowToast(activity_new_ticket.this, response.body() + "", Toast.LENGTH_SHORT);
ResetWidjet();
pd.cancel();
} else {
try {
assert response.errorBody() != null;
MainActivity.ComObj.ShowToast(activity_new_ticket.this, response.errorBody().string(), Toast.LENGTH_LONG);
} catch (IOException e) {
e.printStackTrace();
}
pd.cancel();
}
}
}
#Override
public void onFailure(#Nullable Call<String> call,#Nullable Throwable t) {
if (t != null) {
MainActivity.ComObj.ShowToast(activity_new_ticket.this, t.getMessage(), Toast.LENGTH_SHORT);
}
pd.cancel();
}
});
}
Hope this will help you
Related
I am recently developing new android project. I am trying to save image files into the server directory.
I use Retrofit for HttpConnection with server.
Storing image files into the server directory works well, but the image is not available. Everytime I upload files into the server, it says An error occurred while loading the image. I have been looking for solutions and trying to fix this problem, but I have no idea what causes this problem.
Here is my android code :
ArrayList<MultipartBody.Part> files = new ArrayList<>();
for(int a = 0; a < list.size(); a++) {
// list = uri image list for recyclerview.
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), String.valueOf(list.get(a)));
String fileName = "photo" + a + ".jpg";
MultipartBody.Part filePart = MultipartBody.Part.createFormData("uploaded_file"+a, fileName, fileBody);
files.add(filePart);
}
Call<String> uploadPost = posts.uploadPost(files,hashMap);
uploadPost.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful() && response.body() != null) {
Intent intent = new Intent(upload_sale.this, MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("upload_post",t.getMessage());
}
});
Here is the php code :
$authNum = $_POST['authNum'];
$title = $_POST['title'];
$des = $_POST['description'];
$price = $_POST['price'];
$area = $_POST['area'];
$longitude = $_POST['longitude'];
$latitude = $_POST['latitude'];
$count = $_POST['count'];
$count_int = (int)$count;
if(isset($_FILES['uploaded_file0']['name'])) {
for($i = 0; $i<$count_int; $i++) {
$basename = basename($_FILES['uploaded_file'.$i]['name']);
$file_path = $file_path . $basename;
if(isset($_FILES['uploaded_file'.$i])) {
move_uploaded_file($_FILES['uploaded_file'.$i]['tmp_name'],"./postImage/".$fn.$basename);
$query_img =
"INSERT INTO post_img(path,authNum,img_del,post_authNum)
VALUES ('http://3.36.34.173/postImage/".$fn.$basename."',$authNum,'../postImage/".$fn.$basename."','$post_authNum')
";
}
Thank you in advance.enter image description here
I have a class that add a news with its images by Retrofit.
When Retrofit wants upload images, it shows me this error: FileNotFoundException
I have seen similar questions and answers but nothing was with multiple images.
So I could not find my solution and ask this question.
This is my Retrofit interface's method:
#POST("News/SaveNews")
Call<GetResualt> setNewsLetter(#Body NewsLetterModel newsLetter);
#Multipart
#POST("Products/Post")
Call<GetResualt> uploadNewsLetterImage(#Query("ProductID") String newsLetterId,
#Query("CompanyID") String coId,
#Query("UserID") String uID,
#Query("Token") String token,
#Part List<MultipartBody.Part> files);
This is my onActivityResult after image selecting:
ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
if (result.getData() != null) {
if (result.getData().getClipData() != null) {
int count = result.getData().getClipData().getItemCount();
int currentItem = 0;
while (currentItem < count) {
Uri imageUri = result.getData().getClipData().getItemAt(currentItem).getUri();
imageUriList.add(imageUri);
partNames.add(currentItem + "");
currentItem++;
}
} else if (result.getData().getData() != null) {
imageUriList.add(result.getData().getData());
}
}
NewsLetterModel newsLetter = new NewsLetterModel();
newsLetter.setActiveComment(false);
newsLetter.setActiveLike(false);
newsLetter.setActiveSave(false);
newsLetter.setCategory(category);
newsLetter.setCompanyId(BaseCodeClass.CompanyID);
newsLetter.setCreatorId(BaseCodeClass.userID);
newsLetter.setLinkOut("");
newsLetter.setLinkToInstagram("");
newsLetter.setNewsDescription(description);
newsLetter.setNewsTitle(title);
newsLetter.setShow(true);
newsLetter.setSpare1("#FFFFFF");
newsLetter.setSpare2("#FFFFFF");
newsLetter.setSpare3("#FFFFFF");
newsLetter.setToken(BaseCodeClass.token);
newsLetter.setUserId(BaseCodeClass.userID);
uploadNewsLetter(newsLetter);
}
}
);
This is uploadNewsLetter():
private void uploadNewsLetter(NewsLetterModel newsLetter) {
Retrofit retrofit;
JsonApi api;
retrofit = RetrofitInstance.getRetrofit();
api = retrofit.create(JsonApi.class);
Call<GetResualt> call = api.setNewsLetter(newsLetter);
call.enqueue(new Callback<GetResualt>() {
#Override
public void onResponse(Call<GetResualt> call, Response<GetResualt> response) {
if (response.body().getResualt().equals("100")) {
String newsId = response.body().getMsg();
List<MultipartBody.Part> files;
files = convertUriToFIle(partNames, imageUriList);
uploadNewsImages(newsId, files);
}
}
#Override
public void onFailure(Call<GetResualt> call, Throwable t) {
Log.e("Error", t.getMessage());
}
});
}
This is convertUriToFIle()
private List<MultipartBody.Part> convertUriToFIle(List<String> partNames, List<Uri> imageUriList) {
List<MultipartBody.Part> files = new ArrayList<>();
for (int i = 0; i < imageUriList.size(); i++) {
File file = new File(imageUriList.get(i).getPath());
RequestBody requestFile = RequestBody.create(MediaType.parse(FileUtils.MIME_TYPE_IMAGE), file);
files.add(MultipartBody.Part.createFormData(partNames.get(i), file.getName(), requestFile));
}
return files;
}
And This is uploadNewsMessage:
private void uploadNewsImages(String newsLetterId, List<MultipartBody.Part> files) {
Retrofit retrofit;
JsonApi api;
retrofit = RetrofitInstance.getRetrofit();
api = retrofit.create(JsonApi.class);
Call<GetResualt> call = api.uploadNewsLetterImage(newsLetterId, BaseCodeClass.CompanyID, BaseCodeClass.userID, BaseCodeClass.token, files);
call.enqueue(new Callback<GetResualt>() {
#Override
public void onResponse(Call<GetResualt> call, Response<GetResualt> response) {
if (response.body().getResualt().equals("100")) {
Toast.makeText(getContext(), "خبر با موفقیت ثبت شد", Toast.LENGTH_SHORT).show();
} else {
Log.e("Error", response.body().getResualt() + " " + response.body().getMsg());
}
}
#Override
public void onFailure(Call<GetResualt> call, Throwable t) {
Log.e("Error", t.getMessage());
}
});
}
So base on my code, at first application uploads news and other stuffs except of images, after that it uploads images.
But when it wants upload images it goes to onFailur of retrofit and shows me this error: FileNotFoundException.
In convertUriToFIle() use FileUtils.getFile(context,uri) instead of new File(imageUriList.get(i).getPath());
I have created an application that requires uploading video to the server using FTP. I have searched many options but once the file is uploaded it is not playing back. Can someone help me ?
Here is the data sender parts of my BackgroundSenderService
I used AndroidNetworking library.
My service triggers on some periods to check db that has unsent media file.
For the success and error results I updated db, but you can send Localbroadcasts to trigger some interface elements on UI.
private void checkDbForUpload() {
((MainApp) getApplicationContext()).setMediaSenderIsIdle(false);
MediaModel media = ((MainApp) getApplicationContext()).getFirstUnsendMedia(mContext);
if (media != null) {
if (((MainApp) getApplicationContext()).getHasMission() && ((MainApp) getApplicationContext()).getLastResponse().getCaseId().equals(media.getCaseId())) {
stopThisService();
return;
}
boolean canBeginUpload = ((MainApp) getApplicationContext()).canBeginMediaUpload(mContext);
if (canBeginUpload) {
Log.d(TAG, "checkDbForUpload: we have connected and we have file to upload");
startUploadingProcess(media);
} else {
((MainApp) getApplicationContext()).setMediaSenderIsIdle(true);
stopThisService();
}
} else {
((MainApp) getApplicationContext()).setMediaSenderIsIdle(true);
stopThisService();
}
}
private void startUploadingProcess(MediaModel media) {
int mediaStatus = media.getUploadStatus();
Log.d(TAG, "beginMediaUploadProcess: #" + media.getId() + " Status: " + mediaStatus);
if (media.getRetryCount() > Constants.UPLOAD_ERROR_RETRY_COUNT) {
media.setSessionId("");
saveMediaToDb(media);
}
switch (mediaStatus) {
case Constants.MEDIA_STATUS_UPLOADED:
deleteMediaFromDbAndDisk(media);
checkDbForUpload();
break;
case Constants.MEDIA_STATUS_UPLOADING:
case Constants.MEDIA_STATUS_WAITING:
case Constants.MEDIA_STATUS_ERROR:
if (media.getSessionId() != null && !media.getSessionId().equals("")) {
Log.d(TAG, "startUploadingProcess: has session");
startPutWithoutBody(media);
} else {
Log.d(TAG, "startUploadingProcess: no session");
getMediaEndpoint(media);
}
break;
}
}
private void startPostTask(MediaModel media) {
media.setSessionId("");
setMediaAsWaiting(media);
File file = new File(media.getFile());
String contentType = getMimeType(file.getPath());
setMediaAsUploading(media);
String postUrl = ENDPOINT + "?uploadType=resumable&name=" + createSendingFileName(media);
AndroidNetworking.post(postUrl)
.setTag("uploadRequest")
.setPriority(Priority.HIGH)
.addHeaders("X-Api-Key", Constants.API_KEY_UPLOAD)
.addHeaders("Content-Type", "application/json")
.addHeaders("X-Upload-Content-Type", contentType)
.addHeaders("X-Upload-Content-Length", String.valueOf(file.length()))
.addJSONObjectBody(prepareMetaData(media).toJSON())
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
UploadPostResponseModel responseModel = new UploadPostResponseModel(response);
if (responseModel.getStatusCode() == Constants.HTTP_STATUS_OK) {
media.setSessionId(responseModel.getId());
try {
startPutTask(media);
} catch (Exception e) {
e.printStackTrace();
}
} else {
setMediaUploadError(media);
}
}
#Override
public void onError(ANError anError) {
Log.d(TAG, "onError: " + anError.getErrorDetail());
setMediaUploadError(media);
}
});
}
private void startPutWithoutBody(MediaModel media) {
String putUrl = ENDPOINT + (ENDPOINT.contains("?") ? "&" : "?") + "upload_id=" + media.getSessionId();
AndroidNetworking.put(putUrl)
.setTag("putRequest")
.setPriority(Priority.HIGH)
.addHeaders("X-Api-Key", Constants.API_KEY_UPLOAD)
.addHeaders("Content-Range", getContentRangeString(media))
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
//UploadPostResponseModel responseModel = new UploadPostResponseModel(response);
}
#Override
public void onError(ANError anError) {
setMediaUploadError(media);
}
});
}
private void startPutTask(MediaModel media) {
if (!((MainApp) getApplicationContext()).canBeginMediaUpload(mContext)) {
setMediaAsWaiting(media);
stopThisService();
}
//if fails -> consider using this https://stackoverflow.com/a/54961878/1492681
try {
File tmpDir = mContext.getCacheDir();
File tmpFile = File.createTempFile("TMPFILE", media.getSessionId(), tmpDir);
File orgFile = new File(media.getFile());
int startIndex = (int) media.getUploadedBytes();
Log.d(TAG, "startIndex: " + startIndex);
int bytesLeft = (int) (orgFile.length() - startIndex);
Log.d(TAG, "bytesLeft: " + bytesLeft);
RandomAccessFile f = new RandomAccessFile(media.getFile(), "r");
int len = Constants.CHUNKSIZE;
if (Constants.CHUNKSIZE >= bytesLeft) {
len = bytesLeft;
}
Log.d(TAG, "len: " + len);
byte[] buffer = new byte[len];
f.seek(startIndex);
f.read(buffer, 0, len);
Log.d(TAG, "buffer: " + buffer.length);
int endIndex = startIndex + len;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
bos.write(buffer);
bos.flush();
bos.close();
//send chunk here
String putUrl = ENDPOINT + "?uploadType=resumable&upload_id=" + media.getSessionId();
AndroidNetworking.put(putUrl)
.setTag("putRequest")
.setPriority(Priority.HIGH)
.addHeaders("X-Api-Key", Constants.API_KEY_UPLOAD)
.addHeaders("Content-Range", getContentRangeString(media))
.addFileBody(tmpFile)
.build()
.getAsOkHttpResponse(new OkHttpResponseListener() {
#Override
public void onResponse(Response response) {
switch (response.code()) {
case Constants.HTTP_STATUS_CREATED:
case Constants.HTTP_STATUS_OK:
setMediaAsUploaded(media);
break;
case Constants.HTTP_STATUS_PERMANENT_REDIRECT:
case Constants.HTTP_STATUS_RANGENOTSATISFIABLE:
Log.d(TAG, "onResponse: " + response.toString());
long receivedBytes = parseRange(response);
Log.d(TAG, "uploaded: " + receivedBytes + " of " + orgFile.length());
media.setUploadedBytes(receivedBytes);
setMediaAsUploading(media);
Log.d(TAG, "onResponse: receivedBytesFromServer: " + receivedBytes);
try {
startPutTask(media);
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
setMediaUploadError(media);
break;
}
}
#Override
public void onError(ANError anError) {
setMediaUploadError(media);
}
});
} catch (IOException | ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
setMediaUploadError(media);
}
}
private String getContentRangeString(MediaModel media) {
File file = new File(media.getFile());
long fileLength = file.length();
String contentRange = "bytes */" + fileLength;
Log.d(TAG, "getContentRangeString: " + contentRange);
return contentRange;
}
I'm very new to RxJava and although I have seen multiple questions related to the one I am asking, I can't seem to piece them out altogether.
I have a PostPatrol object containing the following data:
public class PostPatrol {
String checkpoint_name;
String status;
int user;
String detail;
List<String> photos;
public PostPatrol(int cpId, String checkpoint_name, String detail, List<String> photos, String detail) {
this.cpId = cpId;
this.checkpoint_name = checkpoint_name;
this.detail = detail;
this.photos = photos;
this.status = status;
}
//getters and setters
}
What I'm trying to do now is to save a local list of photos into this PostPatrol record, but before that I have to upload the photos one by one with retrofit, get back a url and save that to a list which I then set as the photos for the PostPatrol record.
Once I save all the needed details for a certain PostPatrol record, I then send that again through retrofit.
Currently, I am doing it this way:
I pass the photos to a function to upload the image one by one
The function is like this:
private void uploadImage(List<String> photos, String folder, long requestId) {
final int size = photos.size();
final long reqId = requestId;
for (String path : photos) {
File file = new File(path);
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
RequestBody folderName = RequestBody.create(MediaType.parse("text/plain"), folder);
ApiEndpointInterface apiEndpointInterface = RetrofitManager.getApiInterface();
Call<FileInfo> call4File = apiEndpointInterface.postFile(body, folderName);
call4File.enqueue(new ApiCallback<FileInfo>() {
#Override
protected void do4Failure(Throwable t) {
Log.d(TAG, t.toString());
snackbar = Snackbar.make(viewPendingRequestLayout, R.string.sb_image_upload_error, Snackbar.LENGTH_SHORT);
snackbar.show();
position++;
}
#Override
protected void do4PositiveResponse(Response<FileInfo> response) {
Log.d(TAG, "Uploaded Image");
FileInfo fileDetails = response.body();
listUrls.add(fileDetails.getImage());
position++;
if (position == size) {
postRequest(reqId);
position = 0;
}
}
#Override
protected void do4NegativeResponse(Response<FileInfo> response) {
String bodyMsg = "";
try {
bodyMsg = new String(response.errorBody().bytes());
} catch (IOException e) {
e.printStackTrace();
}
Log.d(TAG, bodyMsg);
snackbar = Snackbar.make(viewPendingRequestLayout, R.string.sb_image_upload_error, Snackbar.LENGTH_SHORT);
snackbar.show();
position++;
}
});
}
}
In do4PositiveResponse I use local variables to keep track whether I have uploaded all the photos before sending them to a function where the list is saved to the PostPatrol record. Sometimes though, I get problems where the photos aren't uploaded at all since it fires too late or too early.
This is my code onpostRequest()
private void postRequest(long requestId) {
if(mapIdPatrol.containsKey(requestId)){
PostPatrol postPatrol = mapIdPatrol.get(requestId);
postPatrol.setPhotos(listUrls);
postPatrolRequest(postPatrol, requestId);
}
listUrls = new ArrayList<>();
}
And finally my code on postPatrolRequest()
private void postPatrolRequest(final PostPatrol postPatrol, final long requestId){
ApiEndpointInterface apiEndpointInterface = RetrofitManager.getApiInterface();
Call<ResponseId> call4Handle = apiEndpointInterface.handleCheckpoint(postPatrol);
call4Handle.enqueue(new ApiCallback<ResponseId>() {
#Override
protected void do4Failure(Throwable t) {
finishUploading();
Log.d(TAG, t.toString());
}
#Override
protected void do4PositiveResponse(Response<ResponseId> response) {
RequestsDataSource.removeRequest(getApplication(),requestId);
finishUploading();
}
#Override
protected void do4NegativeResponse(Response<ResponseId> response) {
finishUploading();
String bodyMsg = "";
try {
bodyMsg = new String(response.errorBody().bytes());
} catch (IOException e) {
e.printStackTrace();
}
Log.d(TAG, bodyMsg);
snackbar = Snackbar.make(viewPendingRequestLayout, getResources().getText(R.string.sb_negative_response), Snackbar.LENGTH_SHORT);
snackbar.show();
}
});
}
I know this is very inefficient and so I would like your help so I can try to find a way around it with the use of RxJava. Thank you.
Is the operation atomic? i.e. if saving some of the photos via Retrofit fails, do you still have to proceed?
Anyway, roughly the solution will be something like that (pseudocode):
Observable<String> urls = Observable.from(listOfPhotoFilePaths)
.flatMapDelayError(path -> { return retrofit.save(readFile(path))})
.toList()
Observable<PostPatrol> pp = urls
.map(list -> { return new PostPatrol(list)})
I want to send a photo from local android gallery to the server http Tomcat. For the communication I'm using retrofit. I've established the connection between device and server, and the programme get into servers function but all objects in params are null.
That's the device function declaration on the client side:
#Multipart
#POST("/monument/photo/upload")
void addMonumentPhoto(#Part("MonumentID") Integer monumentId,
#Part("name") String name,
#Part("subscript") String subscript,
#Part("photo") TypedFile photo,
Callback<Photo> callback);
... and that's how I call it:
photo = _resizePhoto(new File(monument.getUriZdjecie()));
typedFile = new TypedFile("multipart/mixed", photo);
//long bytes = photo.length();
if (photo.exists()) {
MonumentsUtil.getApi().addMonumentPhoto(monument.getIdZabytek(),
"podpis",
"Main photo",
typedFile,
new Callback<Photo>() {
#Override
public void success(Photo aPhoto, Response response) {
monument.setUriZdjecie(aPhoto.getUri());
MonumentsUtil.getApi().addMonument(monument.getNazwa(),
monument.getOpis(),
monument.getDataPowstania(),
monument.getWojewodztwo(),
monument.getUriZdjecie(),
monument.getMiejscowosc(),
monument.getKodPocztowy(),
monument.getUlica(),
monument.getNrDomu(),
monument.getNrLokalu(),
monument.getKategoria(),
monument.getLatitude(),
monument.getLongitude(),
new MonumentsCallback());
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e(TAG, retrofitError.getMessage());
}
});
}
and the server's method:
#RequestMapping(value = "/monument/photo/upload")
public
#ResponseBody
Photo requestMonumentPhotoAdd(#RequestParam(value = "MonumentID", required = false) Integer monumentId,
#RequestParam(value = "name", required = false) String name,
#RequestParam(value = "subscript", required = false) String subscript,
#RequestParam(value = "photo", required = false) MultipartFile file,
HttpServletRequest request) {
Photo photo = new Photo();
if (monumentId != null)
photo.setIdZabytek(monumentId);
photo.setUri(URL + "/images/" + name);
photo.setPodpis(subscript);
photo = monumentsRepo.addPhoto(photo);
String filePath = "D:\\Projects\\Images\\" + monumentId + "_" + photo.getIdZjecia();
if (file != null) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filePath)));
stream.write(bytes);
stream.close();
photo.setUri(filePath);
monumentsRepo.updatePhoto(photo);
return photo;
} catch (Exception e) {
return null;
}
} else {
return null;
}
}
else {
return null;
}
}
Can anybody help me and explain why all objects after geting into the servers method are null?
Maybe method is wrogly writen or the mime field of TypedFile is wrogly chosen but I read that the "multipart/mixed" mime type is for messages with various types of object included in message. I don't have any idea so any advice will be helpful.
Try when creating your TypedFile object to use "image/*" as your mime type. For that "part" it is of that specific type. The "mixed" is likely for the submit as a whole, not the single part that is the file.
typedFile = new TypedFile("image/*", photo);
I also had the similar problems and after few hours trying I finally built image uploading functionality to remote server.
To upload image you need to create the API properly and also need to pass the image properly.
This should work fine for you:
In Retrofit client you need to set up the image as followed:
String photoName = "20150219_222813.jpg";
File photo = new File(photoName );
TypedFile typedImage = new TypedFile("application/octet-stream", photo);
RetrofitClient.uploadImage(typedImage, new retrofit.Callback<Photo>() {
#Override
public void success(Photo photo, Response response) {
Log.d("SUCCESS ", "SUCCESS RETURN " + response);
}
#Override
public void failure(RetrofitError error) {
}
});
API SET UP:
#Multipart
#POST("/")
void uploadImage(#Part("file") TypedFile file, Callback<Photo> callback);
Remote Server Side PHP Code to handle the image:
........
$pic = 'uploaded_images/' . $imagename . '.jpg';
if (!move_uploaded_file($_FILES['file']['tmp_name'], $pic)) {
echo "posted";
}
.........
If it helps any one please recognize me..thanks a lot..