1

I am having trouble uploading an image file along with a string using a post method. The image file does in fact upload to the server, but my attempt to send a string (username) with it has failed. I know I am getting a value for the username because it show's the username in the log when I debug it. Any idea's why this is not working. Here is the doInbackground

protected String doInBackground(String... arg0) {
        try {
            String thePic = (String) arg0[0];
            String name = (String) arg0[1];
            String sourceFileUri = thePic;

            Log.d("THENAME",name);
            Log.d("Pic", thePic);
            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())
            {
                Log.d("CheckFile", "Its a file");
                try {
                    String upLoadServerUri = "http://*Myaddress*.com/upload.php";

                    // 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("fileToUpload", sourceFileUri);
                    conn.setRequestProperty("Uname", name);


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

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

                    dos.writeBytes(lineEnd);
                    String s = Integer.toString(dos.size());
                    Log.d("DOSFILESIZE", s);

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

                    if (serverResponseCode == 200)
                    {
                        Log.d("Server Response",serverResponseMessage);

                        // messageText.setText(serverResponseMessage);
                        //Toast.makeText(this, "File Upload Complete.",Toast.LENGTH_SHORT).show();

                                //recursiveDelete(mDirectory1);

                    }

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

                }
                catch (Exception e)
                {

                    //dialog.dismiss();
                    e.printStackTrace();


                            //messageText.setText("Got Exception : see logcat ");
                            //Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",Toast.LENGTH_SHORT).show();
                    Log.e("Upload file to server Exception", "Exception : "+ e.getMessage(), e);
                }
                // dialog.dismiss();

            } // End else block
            else
            {
                Log.d("No image", "Source is not an iamge file");
            }


        } catch (Exception ex) {
            // dialog.dismiss();

            ex.printStackTrace();
        }
        return "Executed";
    }

And Here's the php code

<?php
$myfile = fopen("userlog.txt", "a");    
fwrite($myfile, "\n\n\n\r\r\n");
fwrite($myfile, "\n\n\n\r\r\n");
fwrite($myfile, date("F j, Y, g:i a") . "\r");
fwrite($myfile, $_SERVER['REMOTE_ADDR']);
fclose($myfile);

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$Uname = $_POST["Uname"];
$status1 = False;
$status2 = False;
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        $uploadOk = 1;
        $con = $con = mysql_connect("localhost:3036","username","password"); 
        if 
        (!$con)
          {
          die('Could not connect: ' . mysql_error());
          }
        mysql_select_db("Rate_It", $con);
        $imgData = file_get_contents($_FILES["fileToUpload"]["tmp_name"]);
        $zero = 0;
        $pid = "NULL";
        $name = "car789";
        $date = "CURDATE()";
        $sql = sprintf("INSERT INTO Picture
        (Pid, Uname, Image, Views, RateTotal, UploadName, UploadDate)
        VALUES
        ('%s', '%s', '%s', '%d', '%d' ,'%s' ,%s)",
        $pid,
        $Uname,
        mysql_real_escape_string($imgData),
        $zero,
        $zero,
        $target_file,
        $date
        );
        $myfile = fopen("test.txt", "a");
        fwrite($myfile, "\n\n\n\r\r\n");
        fwrite($myfile, "\n\n\n\r\r\n");
        fwrite($myfile, date("F j, Y, g:i a"));
        fwrite($myfile, "$sql\n");
        fclose($myfile);
        if ( mysql_query($sql) == TRUE) {
            $status1 = True;
        } 
        else {
            $status1 = False;
        }
        mysql_close($con);

    } else {
        $uploadOk = 0;
    }
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $status2 = True;
    } else {
        $status2 = False;
    }
if($status1 == True && $status2 == True){
    echo "True";
}   
else{
    echo "False";
}

?>
4
  • Your android code does not send a username parameter. So where are you talking about? Commented Apr 28, 2015 at 21:55
  • To check if parameters get posted you only need one code line in your php script: var_dump($_POST);. But then in your android code you need to read 'the response page`. You are not doing that. Google for code 'convert input stream to string'. Commented Apr 28, 2015 at 22:04
  • That's the thing, I'm not sure how to send the name a long with the image file because this code only seems to work when uploading an image file. Commented Apr 29, 2015 at 14:44
  • username. to send the name. Please come to the point. Tell exactly what you want to send. Indicate also the code lines which you tried. Commented Apr 29, 2015 at 14:59

2 Answers 2

1

Directly after

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

add following code:

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

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

Remove all your lines with `Uname in them as that did not work.

Also to grab the page the php script echos back add following code at end of try block:

InputStream in = new BufferedInputStream(conn.getInputStream()); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
    sb.append(line + newLine);
  }
String resultPage = sb.toString();

Looking at your php script its not much you will receive. Only "True" or "False";

`

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!! this worked. I just had to modify the above code for the image file.
1

It works.

This is what it looks like:

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

Much appreciated credit goes to you greenapps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.