1. aka001's Avatar
    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 [table] 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.
    07-19-2020 04:12 PM
  2. JenyLawnnn's Avatar
    Hey, aka001. I had a similar problem as you do now, buddy. I didn't know what was the problem so I decided to use Google in order to find a solution to this issue. I read some forums and according to their advice I decided to change my server, I couldn't afford an expensive one, so I thought that I need to find a cheap variant. I've been searching for 3 hours and I found the site of gthost.com. This site really helped me out, they have dedicated servers which are the cheapest, I compared a lot of prices and I can say that it's worth to use this site because servers have the same specs as the expensive ones have. Also, they managed to set up this thing as fast as possible, which helped me a lot because I needed it very much.
    08-23-2020 03:22 PM

Similar Threads

  1. Automatic Bluetooth volume regulator, would that be useful?
    By ElFrancis99 in forum Ask a Question
    Replies: 2
    Last Post: 07-21-2020, 05:27 PM
  2. Replies: 14
    Last Post: 07-20-2020, 04:15 PM
  3. Starting a Zoom Meeting from the Home Page (Android)
    By Android Central Question in forum Ask a Question
    Replies: 7
    Last Post: 07-19-2020, 03:30 PM
  4. How to delete a station alert?
    By Android Central Question in forum Ask a Question
    Replies: 2
    Last Post: 07-19-2020, 12:03 PM
  5. Why do you have to belong to a social media site for the Android Central app.
    By cardboard60 in forum Samsung Galaxy Note 10 & Note 10+ (2019)
    Replies: 0
    Last Post: 07-19-2020, 05:09 AM
LINK TO POST COPIED TO CLIPBOARD