dougui1977 2015-12-08 08:36
浏览 51
已采纳

将多个图像从Android上传到PHP

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 = "
";
        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));
            }
  • 写回答

1条回答 默认 最新

  • dsg435665475 2015-12-08 12:44
    关注

    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 = "
    ";
                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;
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改