0

I followed this tutorial and this answer on stackoverflow to upload a jpg image to server and save the image path in database using PHP.

The uploading function works but the image path cannot to added to database. Can someone help?

below is a copy of my android code and php code for uploading the image.

class UploadFile extends AsyncTask<String, Void, String> {

    ProgressDialog loading;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        loading = ProgressDialog.show(ViewTaskActivity.this, "Uploading photo", "Please wait...",true,true);
    }

    @Override
    protected void onPostExecute(String message) {
        super.onPostExecute(message);
        loading.dismiss();
        Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
    }

    @Override
    protected String doInBackground(String... arg0) {
        String sourceFileUri = arg0[0];
        String fileName = sourceFileUri;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {
            loading.dismiss();
            Log.e("uploadFile", "Source File not exist :" + uploadFilePath);
            return "Source File not exist";
        }

        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            // 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);

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("journey_id", Integer.toString(journey_id)));
            params.add(new BasicNameValuePair("task_id", Integer.toString(task_id)));

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(params));

            dos = new DataOutputStream(os);

            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();
            Log.d("serverResponseMessage", serverResponseMessage);

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

            if(serverResponseCode == 200){
                return "Photo successfully uploaded";
            }

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

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "Oops! An error occurred";
    }

}

 private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

<?php
$file_path = "uploads/";
$journey_id = $_GET["journey_id"];
$task_id = $_GET["task_id"];

$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {

$con = mysqli_connect("localhost","db_user","somepassword","mydb");
$result = mysqli_query($con, "UPDATE journey_task_pairs SET image_name = '".$_FILES['uploaded_file']['tmp_name']."', image_path = '".$file_path."' WHERE journey_id = $journey_id && task_id = $task_id");
mysqli_close($con);
} else{
    echo "fail";
}
?>
Community
  • 1
  • 1
Angela
  • 1
  • 3
  • What kind of image path are you talking about? – greenapps Mar 15 '17 at 11:00
  • `writer.write(getQuery(params));`. We can not see what you send. Or if there is a path included. Moreover in your php file which identifier would you use to extract the path? – greenapps Mar 15 '17 at 11:03
  • Hi, I've edited my question and add the method getQuery(). Basically I send two integers journey_id and task_id to for mysql update. I'm not sure exactly what kind of image path I want (I'm new to this, sorry), but I hope it can be used to download the image, which will then be displayed in my app. Many thanks! – Angela Mar 15 '17 at 12:19
  • `but the image path cannot to added to database. `. Why not? Which errors? You should let your php script echo() much more. Parameter values. Log strings. At the moment you ard blind as you do not know what is happening. – greenapps Mar 15 '17 at 12:58
  • And of course you should read the php echos() in your Android app from the input stream. – greenapps Mar 15 '17 at 13:01
  • Can you tell me how to read the php echos() in your Android app from the input stream please? My echos are not outputted to Android Studio and I don't know how to view them... – Angela Mar 15 '17 at 13:07
  • `My echos are not outputted to Android Studio ` ?? The php echos are outputted to the Android client who did the post. And you should read them. Code has been published a hundred times on this site. If you only would read some pages tagged android you would already find. – greenapps Mar 15 '17 at 15:05

0 Answers0