Reiner M.
Reiner M.

Reputation: 11

Uploading Multipart-form-data to php

I would like upload any data (Username, Description,..) and a photo from my Android-App to my Server (PHP-Script).

By searching for this i found a solution: How to take a photo and send to HTTP POST request with Android?

By click on my send button, the upload-process starts and the php-script works but the $_POST -Vars are empty? Can anybody help me? My request-code:

[...]
case R.id.btnSend:
    String strName = tName.getText().toString();
    String strEmail = tEmail.getText().toString();
    String strDatum = tDatum.getText().toString();
    String strBeschreibung = tBeschreibung.getText().toString();        

    nvPairs = new ArrayList<NameValuePair>(2);
    nvPairs.add(new BasicNameValuePair("sender", "AndoidApp"));
    nvPairs.add(new BasicNameValuePair("name", strName));
    nvPairs.add(new BasicNameValuePair("email", strEmail));
    nvPairs.add(new BasicNameValuePair("datum", strDatum));
    nvPairs.add(new BasicNameValuePair("beschreibung", strBeschreibung));
    nvPairs.add(new BasicNameValuePair("bild", bmpUrl));

    new UploadTask().execute();
}
[...]

private class UploadTask extends AsyncTask<Void, Void, List<String>> {
    @Override
    protected List<String> doInBackground(Void... params) {
        String response = "";
        try {
            response = new MultipartServer().postData(new URL(postUrl), nvPairs);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }       
}

On the MultipartServer-Code i changed the line:

if ((avatarName = pair.getName()).equals("avatar")) {
    avatarPath = pair.getValue();
}

to this:

if ((avatarName = pair.getName()).equals("bild")) {
    avatarPath = pair.getValue();
}

And the Variables "bmpUrl" and "postUrl" are set correctly at an another line in my code.

Upvotes: 0

Views: 1120

Answers (1)

Reiner M.
Reiner M.

Reputation: 11

Thanks for your help! I found an solution for the problem. The problem was at the Script from How to take a photo and send to HTTP POST request with Android?

I changed it to this:

public class MultipartServer {

    private static final String TAG = "MultipartServer";
    private static final String crlf = "\r\n";
    private static final String twoHyphens = "--";
    private static final String boundary = "AaB03x"; //*****
    private String avatarName = null;
    private String avatarPath = null;

    public String postData(URL url, List<NameValuePair> nameValuePairs) throws IOException {

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000);
        connection.setConnectTimeout(15000);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

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

        FileInputStream inputStream;
        OutputStream outputStream = connection.getOutputStream();
        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

        for (NameValuePair pair : nameValuePairs) {
            dataOutputStream.writeBytes(crlf);
            dataOutputStream.writeBytes(twoHyphens + boundary + crlf);
            dataOutputStream.writeBytes(
                    "Content-Disposition: form-data; name=\""
                    + URLEncoder.encode(pair.getName(), "UTF-8") 
                    + "\";" + crlf);
            dataOutputStream.writeBytes(crlf);
            dataOutputStream.writeBytes(URLEncoder.encode(pair.getValue(), "UTF-8"));
            if (pair.getName().equals("bild")) {
                avatarName = pair.getName();
                avatarPath = pair.getValue();
            }
        }

        // Write Avatar (if any)
        if (avatarName != null && avatarPath != null) {
            dataOutputStream.writeBytes(crlf);
            dataOutputStream.writeBytes(twoHyphens + boundary + crlf);
            dataOutputStream
                    .writeBytes("Content-Disposition: form-data; name=\""
                            + avatarName + "\";filename=\""
                            + new File(avatarPath).getName() + "\";" + crlf);
            dataOutputStream.writeBytes(crlf);

            inputStream = new FileInputStream(avatarPath);
            byte[] data = new byte[1024];
            int read;
            while ((read = inputStream.read(data)) != -1)
                dataOutputStream.write(data, 0, read);
            inputStream.close();

            dataOutputStream.writeBytes(crlf);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
        }

        dataOutputStream.flush();
        dataOutputStream.close();

        String responseMessage = connection.getResponseMessage();
        Log.d(TAG, responseMessage);

        InputStream in = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(in, "UTF-8"));

        StringBuilder response = new StringBuilder();
        char[] b = new char[512];
        int read;
        while ((read = bufferedReader.read(b)) != -1) {
            response.append(b, 0, read);
        }

        connection.disconnect();
        Log.d(TAG, response.toString());
        return response.toString();
    }
}

Upvotes: 1

Related Questions