1

I am trying to upload a file to web server,and also send two variables along with it. The file uploads correctly but the variables are not available at server side .Here is my code

 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);
            conn.setRequestProperty("from", phone);//here
            conn.setRequestProperty("contact", contact);//here
            dos = new DataOutputStream(conn.getOutputStream());
            String urlParameters = "from=" + phone + "&contact=" + contact;
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + fileName + "\"" + lineEnd);

            dos.writeBytes(lineEnd);

At server side which is PHP i am accessing the variables from and contact using $_SERVER['from'];

Can you point out what am i doing wrong or a new approach to it?

I also tried dos.writeBytes("contact=a&from=b");

user2800040
  • 143
  • 2
  • 13

1 Answers1

0

I found the solution on this thread: Sending files using POST with HttpURLConnection

This is what i end typing:

    String boundary =  "*****";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    HttpsURLConnection conn = null;
    DataOutputStream dos = null;
    BufferedReader inStream = null;
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 10*1024*1024;
    String urlString = "https://yoururl.com/phpfile.php";
    try{
        File f = new File("filepath");
        String filename = "filename";
        FileInputStream fileInputStream = new FileInputStream(f);

        // open a URL connection to the Servlet
        URL url = new URL(urlString);
        // Open a HTTP connection to the URL
        conn = (HttpsURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // Use a post method.
        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("upfile", filename);

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

        String name = "myvariable";
        String value = "123456";

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ lineEnd);
        dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
        dos.writeBytes(lineEnd);
        dos.writeBytes(value+ lineEnd);

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"upfile\"; 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)
        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

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

        
        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();
    }
    catch (MalformedURLException ex)
    {
        Log.e("Debug", "erro: " + ex.getMessage(), ex);
    }
    catch (IOException ioe)
    {
        Log.e("Debug", "erro: " + ioe.getMessage(), ioe);
    }

And this is my php relevant code:

try {

if (
    !isset($_FILES['upfile']['error']) ||
    is_array($_FILES['upfile']['error'])
) {
    throw new RuntimeException('Invalid parameters.');
}

switch ($_FILES['upfile']['error']) {
    case UPLOAD_ERR_OK:
        break;
    case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('No file sent.');
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
        throw new RuntimeException('Exceeded filesize limit.');
    default:
        throw new RuntimeException('Unknown errors.');
}

if ($_FILES['upfile']['size'] > 100000) {
    throw new RuntimeException('Exceeded filesize limit.');
}

$variable = $_REQUEST["myvariable"];
//do what you want with the variable you send

if (!move_uploaded_file(
    $_FILES['upfile']['tmp_name'],
    sprintf('myfolder/%s',
        $_FILES['upfile']['name']
    )
)) {
    throw new RuntimeException('Failed to move uploaded file.');
}

echo 'File is uploaded successfully.';

} catch (RuntimeException $e) {

    echo $e->getMessage();

}
user3486626
  • 139
  • 1
  • 6