First of all, thank you for reading my question.
I have a PHP server where I wanted to upload an image from Android devices. When I pick an image in my phone, it is uploaded as a TypedFile (retrofit.mime.TypedFile) to a PHP script. When I want to see the image using a web browser or download the image with FTP client, the image is corrupted. The Log shows me the image bytes and the downloaded file contains these bytes. The first line of the image bytes is:
RIFF WEBPVP8 „ ¥ *,>Ñ`©P(%$##‘Œ9 i;\·û~œdàþ ÚKfëp‡ö~
(WebP mime type?)
My PHP script looks like this:
[...]
$pic = 'uploaded_images/' . $imagename . '.jpg';
if (!move_uploaded_file($_FILES['image']['tmp_name'], $pic)) {
echo "ko";die;
}
[...]
I have also tried fread, fwrite,... and this:
$file = file_get_contents($_FILES['image']['tmp_name']);
if (!$file) {echo 'file ko';die;}
//$file = unpack('h',$file);
if (!file_put_contents($pic, $file)) {echo 'ko';die;}
And some other combinations.
My Android request is (from Intent.ACTION_PICK or Intent.ACTION_IMAGE_CAPTURE):
@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == Activity.RESULT_OK) {
final boolean isCamera;
if (imageReturnedIntent == null) {
isCamera = true;
} else {
final String action = imageReturnedIntent.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = imageReturnedIntent == null ? null : imageReturnedIntent.getData();
}
if (selectedImageUri != null) {
String selectedImagePath = null;
Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, null, null, null, null);
if (cursor == null) {
selectedImagePath = selectedImageUri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
selectedImagePath = cursor.getString(idx);
}
File photo = new File(selectedImagePath);
TypedFile typedImage = new TypedFile("image/*", photo);
// ProgressDialog lazy initialization
if (progress == null) {
progress = new ProgressDialog(getActivity());
progress.setTitle(getString(R.string.updating_data));
progress.setMessage(getString(R.string.please_wait));
progress.setCancelable(false);
progress.setIndeterminate(true);
}
progress.show();
Server.postUserImage(typedImage, imageCallback);
}
}
}
}
Server.postUserImage is a method where I configure the request. The retrofit request interface is:
@Multipart
@POST("/user/image")
void postUserImage(@Part("image") TypedFile image, Callback<User> callback);
I appreciate so much your help. I have spent hours a couple of days looking for the reason and a solution for this. Thank you very much.