2017-04-23 65 views
0

我必須發送圖像從應用程序到PHP服務器以及一些細節。 我已經寫下面的代碼發送的細節,但不知道如何發送圖像。任何人都可以幫助我嗎?如何在Android工作室發送圖像作爲POST

正如你所看到的,我使用Map來發送數據到服務器。但是如何在這裏添加圖片。任何幫助都會有所幫助。

StringRequest strReq = new StringRequest(Request.Method.POST, "URL", 
     new Response.Listener<String>() { 
      @Override 
      public void onResponse(String response) 
      { 
       Toast.makeText(getApplicationContext(), "Response", Toast.LENGTH_LONG).show(); 
      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) {  
       Toast.makeText(getApplicationContext(),"Response", Toast.LENGTH_LONG).show(); 
      } 
     }) 
     { 
      @Override 
      protected Map<String, String> getParams() { 
       Map<String, String> details = new HashMap<>(); 
       details.put("id", session.getKey()); 
       details.put("name", name.toString()); 
       return details; 
      } 
     }; 
strReq.setShouldCache(false); 
AppController.getInstance().addToRequestQueue(strReq); 
+0

如果你可以添加到地圖取決於你的服務器上。但是你沒有告訴我們你的服務器期望文件的方式。此外:你想要的是非常基本的,代碼可以在整個互聯網上的例子中找到,並且可以在這個網站上多次找到。 – greenapps

+0

因爲我使用MAP發送數據,所以PHP服務器會期望在POST變量中...所以對於圖像也是如此... – Nikhil

+0

我建議切換到改造2,多部分文件發送很容易 – Remario

回答

0

您必須將圖像轉換爲字符串。像這樣

public String getStringImage(Bitmap bmp){ 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
    byte[] imageBytes = baos.toByteArray(); 
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); 
    return encodedImage; 
} 

然後你就可以添加圖片到地圖這樣

///Converting Bitmap to String String image = getStringImage(bitmap);

  params.put(KEY_IMAGE, image); 
+0

我有從URL獲取的圖像並將其轉換爲位圖。所以我嘗試使用上面的代碼,但調用compress方法時bmp返回null。 @taimoor – Nikhil

0
   private void uploadImage(final String id, final String name){ 

        String tag_string_req = "req_upImage"; 

        // pDialog.setMessage("Uploading image......"); 
        // showDialog(); 

        //converting image to base64 string 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos); 
        byte[] imageBytes = baos.toByteArray(); 
        long imgSize = imageBytes.length; 
        final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT); 
        // Log.d(TAG, "Image:" + imageString); 


        StringRequest strReq = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { 
         @Override 
         public void onResponse(String response) { 

          Log.d(TAG, "Response:" + String.valueOf(response)); 
          //hideDialog(); 
          try { 
           JSONObject jObj = new JSONObject(response); 
           int success = jObj.getInt("success"); 
           if (success == 1) { 

            Toast.makeText(getApplicationContext(), "Image uploaded successfully", Toast.LENGTH_LONG).show(); 

           } else { 
            // Error occurred in uploading. Get the error 
            // message 
            Toast.makeText(getApplicationContext(), "Some error occurred!. Try again ", Toast.LENGTH_LONG).show(); 

           } 
          } catch (JSONException e) { 
           e.printStackTrace(); 
          } 
         } 

        }, new Response.ErrorListener() { 
         @Override 
         public void onErrorResponse(VolleyError error) { 
          Log.e(TAG, "Uploading Error: " + error.getMessage()); 
          // Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show(); 

          if (error instanceof TimeoutError || error instanceof NoConnectionError) { 

           Toast.makeText(getApplicationContext(), "Communication Error!.", Toast.LENGTH_LONG).show(); 

          } else if (error instanceof AuthFailureError) { 

           Toast.makeText(getApplicationContext(), "Authentication Error!", Toast.LENGTH_SHORT).show(); 

          } else if (error instanceof ServerError) { 

           Toast.makeText(getApplicationContext(), "Internal Server Error!", Toast.LENGTH_SHORT).show(); 

          } else if (error instanceof NetworkError) { 

           Toast.makeText(getApplicationContext(), "Network Error!.", Toast.LENGTH_SHORT).show(); 

          } else if (error instanceof ParseError) { 

           Toast.makeText(getApplicationContext(), "Parse Error!", Toast.LENGTH_SHORT).show(); 

          } 

          hideDialog(); 
         } 


        }) { 
         @Override 
         protected Map<String, String> getParams() { 
          // Posting params 
          Map<String, String> params = new HashMap<String, String>(); 
          params.put("image", imageString); 
          params.put("name", name); 
          params.put("id", id); 


          return params; 
         } 

        }; 

        // disabling volley retry policy 

        strReq.setRetryPolicy(new DefaultRetryPolicy(
          0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); 



        // Adding request to request queue 
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req); 
       } 







       php code 



       <?php 
     require_once 'db_config.php'; 
     if($_SERVER['REQUEST_METHOD']=='POST') 
     { 
     $con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE); 
     $sql ="SELECT image_id FROM table_images ORDER BY image_id ASC"; 

     $res = mysqli_query($con,$sql); 
     $image_id = 0; 
     while($row = mysqli_fetch_array($res)){ 
     $image_id = $row['image_id']; 
     } 
     // saving image in a folder 
     $path = "../uploads/images/$image_id.png"; 

     $actualpath = "http://............./$path"; 

     $response = array(); 

     // check for required fields 
     if (isset($_POST['name']) && isset($_POST['image']) && isset($_POST['id'])) 
     { 
      $name = $_POST['name']; 
      $image_id = $_POST['id']; 
      require_once 'db_Connect.php'; 
      // connecting to db 
      $db = new DB_CONNECT(); 

      // mysql inserting a new row 
      $result = mysql_query("INSERT INTO table_images(name, image, rest_id) VALUES('$name', '$actualpath', '$image_id')"); 

      // check if row inserted or not 
      if ($result) { 
       // successfully inserted into database 
       $response["success"] = 1; 
       $response["message"] = "Image successfully Uploaded."; 

       // echoing JSON response 
       echo json_encode($response); 
      } else { 
       // failed to insert row 
       $response["success"] = 0; 
       $response["message"] = "Oops! An error occurred."; 

       // echoing JSON response 
       echo json_encode($response); 
      } 
     } else { 
      // required field is missing 
      $response["success"] = 0; 
      $response["message"] = "Required field(s) is missing"; 

      // echoing JSON response 
      echo json_encode($response); 
     } 
     require_once 'db_config.php'; 
     require_once 'db_Connect.php'; 
     if(mysqli_query($con,$sql)){ 
      $image = $_POST['image']; 
     file_put_contents($path,base64_decode($image)); 
     /*echo "Successfully Uploaded";*/ 
     } 
     mysqli_close($con); 
     }else{ 
     echo "Error"; 
     } 
     ?>