AsepRoro
AsepRoro

Reputation: 353

How to send data and images from android simultaneously via php

before I ever send data and images with success, but it was done with two different procedures

this is my code to send data

public class HTTPPostData extends AsyncTask {

    @Override
    protected String doInBackground(String... urls) {
        String Result = "";
        byte[] Bresult = null;
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(URL_TO_LOAD);
        try {
            List<NameValuePair> nameValuePairs = LPD;
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            HttpResponse response = client.execute(post);
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
                Bresult = EntityUtils.toByteArray(response.getEntity());
                Result = new String(Bresult, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }
        return Result;
    }

    protected void onPostExecute(String result) {
        // dismiss the dialog after the file was downloaded
        if (!result.toString().trim().equals("")) {
            RunProcedure.StrParam = result;
            RunProcedure.run();
        }
    }
}

and this my code to transfer pic

public boolean TransferFileToHttp(String address_to_handle, String file_name) {
    boolean result = false;
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    // DataInputStream inputStream = null;

    String pathToOurFile = file_name;
    String urlServer = address_to_handle;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    try {
        FileInputStream fileInputStream = new FileInputStream(new File(
                pathToOurFile));

        URL url = new URL(urlServer);
        connection = (HttpURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);

        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream
                .writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                        + pathToOurFile + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

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

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

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

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

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
        result = true;
    } catch (Exception ex) {
        // Exception handling
        result = false;
    }
    return result;
}

how to joining transfer file procedure to post data procedure and retrieve string as a result?

Upvotes: 0

Views: 302

Answers (1)

Murtuza Kabul
Murtuza Kabul

Reputation: 6514

It is absolutely possible to do so. However, you will have to perform some additional steps.

You will first have to convert the image to a base 64 string. Refer to this document http://developer.android.com/reference/android/util/Base64.html

Now the string can be sent as regular json data.

On the server end, you will need a mechanism to convert back the base64 string to image. It is a trivial task though.

There are some disadvantages of this method such as huge size of json request and additional overhead of encoding/decoding.

Upvotes: 1

Related Questions