0

Try to upload multiple images with one request but only the first image is uploaded.

This is the java code:

 protected String doInBackground(String... args) {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "******";
        String result = "Ein Fehler ist aufgetreten";

        String charset = "UTF-8";
        String insertedReportID;

        try
        {
            insertedReportID = args[0];

                /* BEGIN - ADD LOGIN CREDENTIALS TO THE QUERY */
            final String authKeyMail = "authMail";
            final String authKeyPW = "authPW";
            Context mContext = getContext();
            SharedPreferences mPrefs = mContext.getSharedPreferences("privPrefs", Context.MODE_PRIVATE);

            String email = mPrefs.getString(authKeyMail, "default");
            String pw = mPrefs.getString(authKeyPW,"default");

            HashMap<String, String> params = new HashMap<>();
            params.put("emailadr", email);
            params.put("passwrt", pw);

            StringBuilder sbParams = new StringBuilder();
            int i = 0;
            for (String key : params.keySet()) {
                try {
                    if (i != 0){
                        sbParams.append("&");
                    }
                    sbParams.append(key).append("=")
                            .append(URLEncoder.encode(params.get(key), charset));

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                i++;
            }
                /* END - ADD LOGIN CREDENTIALS TO THE QUERY */


            URL url = new URL(UPLOAD_URL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();
            // allow  input and output
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            // use POST way

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);

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


            //BEGIN - ADD LOGIN CREDENTIALS TO THE UPLOADER
            dos.writeBytes(twoHyphens + boundary + end);
            //"emailadr" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['emailadr']
            dos.writeBytes("Content-Disposition: form-data; name=\"emailadr\""+ end);
            dos.writeBytes(end);

            dos.writeBytes(email);
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + end);

            //"passwrt" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['passwrt']
            dos.writeBytes("Content-Disposition: form-data; name=\"passwrt\""+ end);
            dos.writeBytes(end);
            dos.writeBytes(pw);
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + end);
            //END - ADD LOGIN CREDENTIALS TO THE UPLOADER

            //"playgroundID" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['equipmentID']
            dos.writeBytes("Content-Disposition: form-data; name=\"reportID\""+ end);
            dos.writeBytes(end);
            dos.writeBytes(insertedReportID);
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + end);
            //END - ADD LOGIN CREDENTIALS TO THE UPLOADER

            //"playgroundID" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['equipmentID']
            dos.writeBytes("Content-Disposition: form-data; name=\"imageCounter\""+ end);
            dos.writeBytes(end);
            dos.writeBytes(String.valueOf(uploadImages.size()));
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + end);
            //END - ADD LOGIN CREDENTIALS TO THE UPLOADER

            for(int j=0;j<uploadImages.size();j++){
                //"image_file" MUST BE THE EXACT SAME NAME AS IN PHP $_FILES['image_file']
                dos.writeBytes("Content-Disposition: form-data; name=\"image_file"+String.valueOf(j)+"\"; filename=\""
                        + uploadImages.get(j).substring(uploadImages.get(j).lastIndexOf("/") + 1)
                        + "\""
                        + end);
                dos.writeBytes(end);

                FileInputStream fis = new FileInputStream(uploadImages.get(j));
                byte[] buffer = new byte[8192]; // 8k
                int count = 0;

                while ((count = fis.read(buffer)) != -1)
                {
                    dos.write(buffer, 0, count);
                }
                fis.close();

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

                Log.d("asdasd", "image_file"+uploadImages.get(j));
            }
            dos.flush();

            InputStream is = httpURLConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            result = br.readLine();

            dos.close();
            is.close();
            httpURLConnection.disconnect();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return result;
    }

Php Code Snippet:

if (isset($_POST)) {
    $imageCounter = $_POST['imageCounter'];

    for ($i = 0; $i < $imageCounter; $i++) {
        if ($_POST['reportID'] == "") {
            die('Hier ist etwas schiefgelaufen (Code 100)');
        }

        // check $_FILES['ImageFile'] not empty
        if (!isset($_FILES['image_file'.$i]) || !is_uploaded_file($_FILES['image_file'.$i]['tmp_name'])) {
            die('Image file is Missing!'); // output error when above checks fail.
        }

        //get uploaded file info before we proceed
        $image_name = $_FILES['image_file'.$i]['name']; //file name
        $image_size = $_FILES['image_file'.$i]['size']; //file size
        $image_temp = $_FILES['image_file'.$i]['tmp_name']; //file temp

        $image_size_info = getimagesize($image_temp); //gets image size info from valid image file

Now the problem is that only the first image is uploaded and entered into the db.

I think there is something wrong with both sides (Java/Php). Firstly with java because I can only receive one image on the php side.

I also got this working with ajax by using such a form:

<form action="../php/ajax/views/reports/uploadReportImages.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
                                    <div class="form-group">
                                        <span id="durchsuchenBtn" class="btn btn-info btn-file">
                                            <i class="fa fa-search fa-fw"></i> Durchsuchen <input name="image_file[]" id="imageInput" type="file" multiple="true">
                                        </span>
                                    </div>
                                </form>

Now I'm not sure how to translate name="image_file[]" id="imageInput" type="file" multiple="true" from the html form to java so I can send the images saved in "uploadImages"-String-ArrayList to the php script.

Any suggestion/help would be very nice.

As a little addition I don't want to use any library to handle the upload process...

I think everything is just fine except it only adds one file so the mistake must be here:

for(int j=0;j<uploadImages.size();j++){
                //"image_file" MUST BE THE EXACT SAME NAME AS IN PHP $_FILES['image_file']
                dos.writeBytes("Content-Disposition: form-data; name=\"image_file"+String.valueOf(j)+"\"; filename=\""
                        + uploadImages.get(j).substring(uploadImages.get(j).lastIndexOf("/") + 1)
                        + "\""
                        + end);
                dos.writeBytes(end);

                FileInputStream fis = new FileInputStream(uploadImages.get(j));
                byte[] buffer = new byte[8192]; // 8k
                int count = 0;

                while ((count = fis.read(buffer)) != -1)
                {
                    dos.write(buffer, 0, count);
                }
                fis.close();

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

                Log.d("asdasd", "image_file"+uploadImages.get(j));
            }
Janine Kroser
  • 444
  • 2
  • 6
  • 23
  • you can use `Multipart Entity` of `httpasyncclient` get an idea how to do that [HERE](http://stackoverflow.com/Questions/12422541/how-to-send-multiple-images-to-server-using-multipartentity-from-android) – Devendra Singh Dec 08 '15 at 10:28

1 Answers1

0

Ok it hasn't worked because I arranged this line wrong:

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

Here is my working java code:

protected String doInBackground(String... args) {
            String end = "\r\n";
            String twoHyphens = "--";
            String boundary = "******";
            String result = "Ein Fehler ist aufgetreten";

            String charset = "UTF-8";
            String insertedReportID;

            try
            {
                insertedReportID = args[0];

                    /* BEGIN - ADD LOGIN CREDENTIALS TO THE QUERY */
                final String authKeyMail = "authMail";
                final String authKeyPW = "authPW";
                Context mContext = getContext();
                SharedPreferences mPrefs = mContext.getSharedPreferences("privPrefs", Context.MODE_PRIVATE);

                String email = mPrefs.getString(authKeyMail, "default");
                String pw = mPrefs.getString(authKeyPW,"default");

                HashMap<String, String> params = new HashMap<>();
                params.put("emailadr", email);
                params.put("passwrt", pw);

                StringBuilder sbParams = new StringBuilder();
                int i = 0;
                for (String key : params.keySet()) {
                    try {
                        if (i != 0){
                            sbParams.append("&");
                        }
                        sbParams.append(key).append("=")
                                .append(URLEncoder.encode(params.get(key), charset));

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    i++;
                }
                    /* END - ADD LOGIN CREDENTIALS TO THE QUERY */


                URL url = new URL(UPLOAD_URL);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url
                        .openConnection();
                // allow  input and output
                httpURLConnection.setDoInput(true);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setUseCaches(false);
                // use POST way

                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
                httpURLConnection.setRequestProperty("Charset", "UTF-8");
                httpURLConnection.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);

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


                //BEGIN - ADD LOGIN CREDENTIALS TO THE UPLOADER
                dos.writeBytes(twoHyphens + boundary + end);
                //"emailadr" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['emailadr']
                dos.writeBytes("Content-Disposition: form-data; name=\"emailadr\""+ end);
                dos.writeBytes(end);

                dos.writeBytes(email);
                dos.writeBytes(end);
                dos.writeBytes(twoHyphens + boundary + end);

                //"passwrt" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['passwrt']
                dos.writeBytes("Content-Disposition: form-data; name=\"passwrt\""+ end);
                dos.writeBytes(end);
                dos.writeBytes(pw);
                dos.writeBytes(end);
                dos.writeBytes(twoHyphens + boundary + end);
                //END - ADD LOGIN CREDENTIALS TO THE UPLOADER

                //"playgroundID" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['equipmentID']
                dos.writeBytes("Content-Disposition: form-data; name=\"reportID\""+ end);
                dos.writeBytes(end);
                dos.writeBytes(insertedReportID);
                dos.writeBytes(end);
                dos.writeBytes(twoHyphens + boundary + end);
                //END - ADD LOGIN CREDENTIALS TO THE UPLOADER

                for(int j=0;j<uploadImages.size();j++){
                    //"image_file" MUST BE THE EXACT SAME NAME AS IN PHP $_FILES['image_file']
                    dos.writeBytes("Content-Disposition: form-data; name=\"image_file[]\"; filename=\""
                            + uploadImages.get(j).substring(uploadImages.get(j).lastIndexOf("/") + 1)
                            + "\""
                            + end);
                    dos.writeBytes(end);

                    FileInputStream fis = new FileInputStream(uploadImages.get(j));
                    byte[] buffer = new byte[8192]; // 8k
                    int count = 0;

                    while ((count = fis.read(buffer)) != -1)
                    {
                        dos.write(buffer, 0, count);
                    }
                    fis.close();
                    dos.writeBytes(end);
                    dos.writeBytes(twoHyphens + boundary + end);
                }

                dos.close();

                InputStream is = httpURLConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                result = br.readLine();

                is.close();
                httpURLConnection.disconnect();
            } catch (Exception e)
            {
                e.printStackTrace();
            }
            return result;
        }
Janine Kroser
  • 444
  • 2
  • 6
  • 23