• 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

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.

Help Package installer keeps stopping

Is there no other option ?
If you have installed the app from google playstore then search the app's name in playstore and go to the app's page. On that page there will be options to open the app and uninstall the app. Choose the option of unistall and then the app will be successfully uninstalled. Atleast in my case it did uninstall.
Even if you installed the app from some other source then also you can check the app on playstore if its available there.

Incompatibility with Chrome and windows mail

@PDN First off my apologies. I never realised the Tab / Box I click from the Windows Tab. that directly opens Outlook Mail (with a Calendar) was actually called Mail and not "for my mail".
I wouldn't listen to a word more from me from here, but can we get to the nub again.
The Mail App then came with Windows (I preferred calling them Programs)
I tried to recreate from an Outlook email link what happens to you.
Is it just Comcast email?
If you click on a link in a Live / Outlook email will that always open in Edge, but not other email addresses you have added to the Mail App.

You can have the Mail app/program open the Chrome browser by default instead of Edge. I checked how.
Is it only You Tube links?

Personally, I have Outlook mail on the Mail app, Yahoo Mail on the Edge browser, with a shortcut box, GMX work mail on an Opera broweer, and Gmail on the Chrome browser. On my phone I have seperate apps for each.

im still struggling with your initial query where Chrome blinks and needs confirmation for a link (from which email) , where Edge opens directly, as it should.

We probably still haven't answered your questions.
Do you want one email program / app to open all addresses?

Admittedly I don't get email notifications on my pc other than the Outlook app, I just open Edge etc and tap Yahoo for example.


Is it just an extra step to Chrome for a link.
Do you paste a link in to Chrome?
I don't know what happens, and a Screenshot from you might contain personal information, so hopefully this will at least bump your questions for someone to see.

Added: Everyone has good experience of their preferences, but here's a recent list of recommended Windows based Email apps from a good source (where email is concerned, they call these email clients - I feel like a 3 year old explaining to a professor) :

https://www.techradar.com/uk/best/best-email-clients

Photo Auto Upload

My A40 does not automatically upload my photos to my Google account like my other phones (mostly MOTO's) do. I have to view them in the Google Photos App before they turn up on my Google drive. As soon as I open the Photos App, I see the little upload icon top right. I've played around with the settings and Googled for fixes but drawn a blank.

Is there a setting which automatically uploads them when I have WiFi access?

Pete

BIG Deezer problem

These subscription people usually have a tight control on the sign up and cancellation terms and conditions, and if you didn't follow them to the letter I think you will have some difficulty in getting back what you have paid. There should be no problem in cancelling future payments. You can normally do that within any monthly period of the subscription but you don't get any credit for days left in that subscription period.

EDIT.. I don't know why I picked this up, it's going back to 2018!!

Ignore me, I've lost the plot!!!!!!:rolleyes:

US996 on Oreo ULBL and rooted

I created a TAR backup of /data/media using TWRP/terminal booted into recovery.

I did a factory reset (actually just the DATA partition and then rebooted the phone into SYSTEM (Normal boot). Went thru all the "new phone" rigmarole successfully.

The went into recovery mode again and restored the TAR file. Figured it would restore the deice back to what it was before i was reset. NOPE!! Restoring the /data/media directory brought it back as though I had FACTORY RESET again.

I've done this before, (but probably on Nougat) and it used to work. Anybody have an idea; I'm stumped.

Thanks Boowho??

tasker entry and exit task behaviour

Hi,

I created a tasker profile with an entry and exit task:

entry task: When I connect to a wifi network a log is added to a file like: 200718-21:08 Conn: <AP-name> <no newline>

exit task: When I disconnect my exit task completes the log with something like: , disc after <period>.

This results in a log file with entries like:
200718-21:08 Conn: <AP-name>, disc after <period>.
Most of the time the logfile is fine but occasionally the log file is different, showing the entry task text multiple times before the exit task text.

It seems like the entry task is executed multiple times and I have no clue why.

Of course there are ways around but I still would like to understand the why. Can anyone explain?

Filter

Back
Top Bottom