Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection and writing file WITH DATA

I'm trying to post a file and data to my server from an Android java script (to my php), it seems I'm pretty much there, but someone PLEASE help me, as I can't seem to format the name/value part (the FILE uploads perfect, but it doesn't send the name value :( )

JAVA:

                try{
         int serverResponseCode = 0;
            final String upLoadServerUri = "http://myUrl/upload_file_functions.php";
          String fileName = "/mnt/sdcard/myFile.dat";

            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("/mnt/sdcard/myFile.dat"); 


                     // 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("file", fileName); 
                       conn.setRequestProperty("gmail", names[0]);
                       conn.setRequestProperty("phn", phn);

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

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

                       dos.writeBytes(twoHyphens + boundary + lineEnd);


                       String data = URLEncoder.encode("gmail", "UTF-8") + "=" + URLEncoder.encode(names[0], "UTF-8");
                       dos.writeBytes(data);



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





                       dos.writeBytes("Content-Disposition: form-data; name=\"" + names[0] + "\"" + lineEnd);
                       dos.writeBytes("Content-Type: text/plain"+lineEnd);
                       dos.writeBytes(lineEnd);
                       dos.writeBytes(names[0]);
                       dos.writeBytes(lineEnd);

                       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


                       //*************************



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

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

                       if(serverResponseCode == 200){

                           // it worked !
                       }    




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

        }catch (Exception e){

        }

It doesn't work, the FILE sends fine, but I can't get a freaking key/name to send ("gmail:"names[0]) I've also tried:

 // 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("Content-Type", "multipart/form-data;boundary=" + boundary);

                           conn.setRequestProperty("gmail", names[0]);

dos.writeBytes(twoHyphens + boundary + lineEnd);

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

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

                           dos.writeBytes(twoHyphens + boundary + lineEnd);

DOESN'T WORK. I've tried:

dos.writeBytes("Content-Disposition: form-data; name=\"gmail\";filename=\""+ names[0] + "\"" + lineEnd);

Doesn't WORK! WTF! I've programmed for years in C++ and python, it's a simple thing! But I can't figure this out I need help, if you know how to do it PLEASE DO TELL because I've spent two days banging my head against the wall. I'm not lazy I spent 32+ f'n hours on this please I beg you..

What I WANT to happen: send the file for upload, along with the value (name=gmail value=names[0]; name=phn value=phn), so that the email is associated to the file on my server. What IS happening: file is uploading fine, but data is not passed (the name/value pairs are not sent)

PHP:

    <?php

    set_time_limit(100);


    //need to get email also (gmail address of user)

    //************************************************
    if ($_FILES["file"]["error"] > 0)
      {
      echo "Error: " . $_FILES["file"]["error"] . "<br>";
      }
    else
      {
      echo "Upload: " . $_FILES["file"]["name"] . "<br>";
      echo "Type: " . $_FILES["file"]["type"] . "<br>";
      echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
      echo "Stored in: " . $_FILES["file"]["tmp_name"];
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }



    function Three(){

    $to =    '[email protected]';
    $subject =   $_POST['phn'] . " " . $_POST['gmail'];
    $bound_text =   "file";
$bound =    "--".$bound_text."\r\n";
$bound_last =   "--".$bound_text."--\r\n";

$headers =  "From: [email protected]\r\n";
$headers .= "MIME-Version: 1.0\r\n"
    ."Content-Type: multipart/mixed; boundary=\"$bound_text\"";

$message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n"
    .$bound;

$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
    ."Content-Transfer-Encoding: 7bit\r\n\r\n"
    ."hey my <b>good</b> friend here is a picture of regal beagle\r\n"
    .$bound;

$file = file_get_contents("http://myURL/upload/myFile.dat");

$message .= "Content-Type: image/jpg; name=\"myFile.dat\"\r\n"
    ."Content-Transfer-Encoding: base64\r\n"
    ."Content-disposition: attachment; file=\"myFile.dat"\r\n"
    ."\r\n"
    .chunk_split(base64_encode($file))
    .$bound_last;
@mail($to, $subject, $message, $headers);

//delete files
$fileArray=array($_FILES["file"]["name"],"myfile.dat","myfile.dat");
foreach($fileArray as $value){
 if(file_exists($value)){
  unlink($value);
 }
}

chdir($old_path);
}

function runAll(){
 One();
 Two();
 Three();
}
runAll();
$randx=null;
unset($randx);


?>

PLEASE HELP! The JAVA is not sending the name='gmail' value=names[0], nor the name='phn' value=phn ..

like image 807
Diamond Dave Avatar asked Mar 28 '26 18:03

Diamond Dave


1 Answers

You should really read up on a few things: HTTP (and the distinction between request header fields and the post body), and the structure of a multipart/form-data post body.

This:

         conn.setRequestProperty("Connection", "Keep-Alive");
         conn.setRequestProperty("ENCTYPE", "multipart/form-data");
         conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
         conn.setRequestProperty("file", fileName); 
         conn.setRequestProperty("gmail", names[0]);
         conn.setRequestProperty("phn", phn);

sends a few request headers, which is fine for Content-Type and such, but not necessarily for the data you're posting. Lose all but the Content-Type line.

This:

         dos.writeBytes(twoHyphens + boundary + lineEnd); 

is the right way to start a post field (or file), you should output this for every posted field.

This:

         dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

signals that all fields have been sent, you should send this as the very last line.

Either use something like Wireshark to see what your final request looks like (either side will do; the device doing the request or the server handling it), or log your request so you can inspect it, and see if it is perfect. It has to be nearly perfect for the webserver/php to process it correctly.

like image 193
mvds Avatar answered Apr 01 '26 08:04

mvds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!