• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Android Retrofit: Unable to upload image to server. Uploads 0 kb image when using file_put_contents

AKA001

Newbie
Hi,


I am trying to use retrofit to upload an image from the android device to mysql database and server. Below is the java code that I am using for uploading the image:

```

private void uploadImage() {




Bitmap fullSizeBitmap = BitmapFactory.decodeFile(pathToFile);

Bitmap reducedBitmap = ImageResizer.reduceBitmapSize(fullSizeBitmap,240000);

File reducedFile = getBitmapfile(reducedBitmap);




MultipartBody.Part parts = null;





Retrofit retrofit = NetworkClient.getRetrofit();

UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);

RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), reducedFile);




parts = MultipartBody.Part.createFormData("newimage", reducedFile.getName(),requestBody);


// RequestBody someData = RequestBody.create(MediaType.parse("text/plain"),"This is a new image");



Call call = uploadAPIs.uploadImage(parts);





call.enqueue(new Callback() {

@override

public void onResponse(Call call, retrofit2.Response response) {




Toast.makeText(Bottom_up.this, "uploaded image", Toast.LENGTH_SHORT).show();

}


@override

public void onFailure(Call call, Throwable t) {

Toast.makeText(Bottom_up.this, "upload image error", Toast.LENGTH_SHORT).show();


}

});



}

//image upload to server and reduce size

private File getBitmapfile(Bitmap reducedBitmap) {

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "reduced_file");

//"reduced_file");


ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();

reducedBitmap.compress(Bitmap.CompressFormat.JPEG,40,byteArrayOutputStream);

byte[] imgbytes=byteArrayOutputStream.toByteArray();

try {

file.createNewFile();

FileOutputStream fos = new FileOutputStream(file);

fos.write(imgbytes);

fos.flush();

fos.close();

return file;

} catch (Exception e) {

e.printStackTrace();

}

return file;

}

```




The pathtofile in the above function is coming from the below:

```

private void dispatchPictureTakenAction() {

Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

if (takePic.resolveActivity(getPackageManager())!=null) {


photoFile = createPhotoFile();


if (photoFile != null) {

//path to file in below variable

pathToFile = photoFile.getAbsolutePath();

Uri photoURI = FileProvider.getUriForFile(Bottom_up.this,"com.android.cameraandroid.fileprovider",photoFile);

takePic.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);


startActivityForResult(takePic, 1);


}


}

}


private File createPhotoFile() {

String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

File image =null;

try {

image = File.createTempFile(name,".jpg", storageDir);

} catch (IOException e) {

Log.d("myLog","Exception: " + e.toString());

}

return image;


}


```


Below is the api client code:

```

public class NetworkClient {


private static Retrofit retrofit;

private static String BASE_URL = "http://192.168.2.13/Dashboard/";


public static Retrofit getRetrofit() {

OkHttpClient okHttpClient = new OkHttpClient.Builder().build();


if (retrofit == null) {

retrofit = new Retrofit.Builder().baseUrl(BASE_URL).

addConverterFactory(GsonConverterFactory.create()).

client(okHttpClient).

build();

}

return retrofit;



}



}


```


Below is the API interface code (insert is the server side PHP script):


```

public interface UploadAPIs {

@Multipart

@Post ("insert")

Call<RequestBody> uploadImage(@part MultipartBody.Part reducedFile);



}


```


Now, in the PHP script I have tried the following:


1. Use file_put_contents (it uploads a blank image i.e. 0 kb image on the server):

```

$image = $_POST["newimage"];

$sql ="SELECT id FROM
ORDER BY id ASC";



$res = mysqli_query($connect,$sql);

$id = 0;



while($row = mysqli_fetch_array($res)){

$id = $row['id'];

}



$upload_paths = "Photo/$id.jpg";

file_put_contents($upload_paths,$image);

```


2. Use move_uploaded_file (it throws an error for undefined index for newimage and errors the upload. It seems like the key value for newimage is not being sent to the php script):


```

$image = $_FILES["newimage"];


if (move_uploaded_file($image, $upload_paths))


{

echo “Successfully uploaded $image.";


}

else

{

echo "Error uploading THIS $image.";

}


````


Can anyone please let me know what I could be missing or doing incorrect in the above code?


Appreciate your help in advance.
 
Back
Top Bottom