Home » Php » Unable to upload the image to server on android app using php api

Unable to upload the image to server on android app using php api

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am creating an app in android for uploading pictures on the server. For that I created an api in php. But I am not able to upload the picture on server
Here is my android code

FileInputStream fileInputStream = new FileInputStream(
                        sourceFile);
                // URL url = new URL(
                // "http://www.mystashapp.com/Loyalty/mobileservice.php?action=upload_image");
                URL url = new URL(
                        "http://www.mvcangularworld.com/api.php");
                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + fileName + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                InputStreamReader isr = new InputStreamReader(
                        conn.getInputStream());

                BufferedReader br = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    sb.append(line);
                }

                isr.close();
                br.close();

                JSONObject json = new JSONObject(sb.toString());
                filePath = json.optString("filepath");

                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);

                if (serverResponseCode == 200) {
                    // Toast.makeText(context, "File Upload Completed.",
                    // Toast.LENGTH_LONG).show();
                    Log.e("message", "image upload complete");
                }

                // close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

And here is my php api

<?php

$target_path = 'andriod/';  // Path to move uploaded files
$response = array();

$file_upload_url = $target_path;
//$filename = $_POST['filename']; 
 $server_ip = "http://www.mvcangularworld.com";//gethostbyname(gethostname());
// final file url that is being uploaded
$file_upload_url = $server_ip . '/' . $target_path;

 if (isset($_FILES['fileName']['name'])) {
    $target_path = $target_path . basename($_FILES['fileName']['name']);
    // reading other post parameters


    $response['file_name'] = basename($_FILES['fileName']['name']);

    try {
        // Throws exception incase file is not being moved
        if (!move_uploaded_file($_FILES['fileName']['tmp_name'], $target_path)) 
        {
            // make error flag true
            $response['error'] = true;
            $response['message'] = 'Could not move the file!';
        }

        // File successfully uploaded
         //echo $file_upload_url . basename($_FILES['filename']['name']);
        $response['message'] = 'File uploaded successfully!';
        $response['error'] = false;
        $response['file_path'] = $file_upload_url . basename($_FILES['fileName']['name']);
    } 
    catch (Exception $e) {
        // Exception occurred. Make error flag true
        $response['error'] = true;
        $response['message'] = $e->getMessage();
    }
} else { 
    // File parameter is missing
    $response['error'] = true;
    $response['message'] = $_FILES['fileName']['name'];
}

// Echo final json response to client
echo json_encode($response, JSON_UNESCAPED_SLASHES);
?>

It always throw me in else condition and give me the this reponse in return

{"error":true,"message":null}

I am unable to upload my file to the server. Any body knows the issue please tell me.

How to&Answers:

change this line

conn.setRequestProperty("uploaded_file", fileName);

to

conn.setRequestProperty("fileName", fileName);

and this also

dos.writeBytes("Content-Disposition: form-data; name=\"filename\";filename=\""
                    + fileName + "\"" + lineEnd);

you are retriving file as filename in php, but passing it with name uploaded_file. Change its name it will work

Answer:

1) Convert the image into string as byte array or base64 (string format).

reference1

reference2

2) your php api, try to receive the string as RESTful (as JSON) or normal.

3) in your php, convert the string to image. but should be restrict the image format (e.g mobile will send .jpeg and php will convert the string .jpeg)

reference3

reference4

or

you can search at google as “android upload image to server”