2016-01-11 4 views
1

В моей деятельности А, он имеет ListView, где изображение и текст были получить от деятельности Б.получить неприятности, когда нужно сохранить путь изображения в MySQL

Activtiy ListView с изображением и текстом

enter image description here

Когда нажата кнопка сохранения, я хочу сохранить путь изображения и текст в mysql через php, а изображение будет сохранено в каталоге.

Activiy

public void uploadImageAndText(ArrayList<ImageAndText> listItems, final String id) { 
      JSONArray jsonArray = new JSONArray(); 
      try { 
       for (ImageAndText i : listItems) { 
        JSONObject object = new JSONObject(); 
        String type = i.getType(); 
        String[] Type = type.split(":"); 
        object.put("type", Type[1]); 
        Toast.makeText(getApplicationContext(), Type[1], Toast.LENGTH_LONG).show(); 
        String amount = i.getAmount(); 
        String[] Amount = amount.split(":"); 
        object.put("amount", Amount[1]); 
        String description = i.getDescription(); 
        String[] Description = description.split(":"); 
        object.put("description", Description[1]); 
        Bitmap uploadImage = i.getImage(); 
        String image = getStringImage(uploadImage); 
        object.put("image", image); 
        object.put("ts_id", id); 
        jsonArray.put(object); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      AddStaff ru = new AddStaff(jsonArray); 
      ru.execute(); 

     } 

     class AddStaff extends AsyncTask<String, Void, String> { 
      ProgressDialog loading; 

      JSONArray jsonArray; 

      AddStaff(JSONArray jsonArray) { 
       this.jsonArray = jsonArray; 
      } 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       loading = ProgressDialog.show(AddClaims.this, "Please Wait", null, true, true); 
      } 

      @Override 
      protected String doInBackground(String... params) { 
       HashMap<String, String> data = new HashMap<String, String>(); 
       data.put("listItems", jsonArray.toString()); 
       RequestHandler rh = new RequestHandler(); 
       String result = rh.sendPostRequest(Configs.STAFF_BENEFIT, data); 
       return result; 
      } 

      @Override 
      protected void onPostExecute(String s) { 
       super.onPostExecute(s); 
       loading.dismiss(); 
       Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show(); 
      } 
     } 


     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; 
     } 
    } 

PHP

<?php 
    if($_SERVER['REQUEST_METHOD']=='POST'){ 

     if(!empty($_POST['listItems'])){ 

      $mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb"); 
      if($mysqli->connect_errno) echo "Failed to connect to MySQL";/* try not to reveal too much info! */ 

      /* The example you followed had this line! */ 
      $image = $_POST['image']; 

      $listItems = json_decode($_POST['listItems'], true); 

      /* This never gets called - should it? */ 
      $sql="SELECT id FROM staff_benefit ORDER BY id ASC"; 
      /* 
       This fetches ALL ids from the staff_benefit table 
       so which ID do you need? Iterating through the 
       recordset will effectively return the last one! 
      */ 

      $id=0; 



      /* 
       I assume that $id is supposed to get 
       the value from th above sql query??? 
      */  
      $res=$mysqli->query($sql); 
      while($rs=$res->fetch_object()) $id=$rs->id; 

      $path="$id.png"; 
      $actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path"; 


      /* Use only placeholders in your prepared statement */ 
      $sql="INSERT INTO `staff_benefit` (`type`, `amount`, `description`, `image`, `ts_id`) VALUES (?, ?, ?, ?, ?)"; 
      $stmt=$mysqli->prepare($sql); 


      /* Save the image to disk: I prefer to use the actual path for storing files */ 
      $pathelements=array(realpath($_SERVER['DOCUMENT_ROOT']), 'CRUD', 'PhotoUpload', '');/* empty entry adds trailing slash to path */ 
      $savepath = realpath(implode(DIRECTORY_SEPARATOR, $pathelements)) . "{$id}.png"; 

      $bytes=file_put_contents($savepath, base64_decode($image)); 
      if(!$bytes){ 
       echo 'Error saving image'; 
      } 

      if ($stmt && $bytes) { 
       foreach($listItems as $item){ 

        $stmt->bind_param('sssss', $item['type'], $item['amount'], $item['description'], $actualpath, $item['ts_id']); 
        $res=$stmt->execute(); 

        if(!$res) echo 'Query failed with code: '.$stmt->errno;/* Again, not too much info */ 
       } 
      } 
      $mysqli->close(); 
     } 
    } 
?> 

Когда Нажмите на изображение в каталоге, не может отображать изображение, так как файл пуст

enter image description here

+0

Эта ошибка появляется в php или java? –

+0

В sql вы используете 'file_put_contents()' для изображения -, который вернет количество написанных байтов, а не путь. Кроме того, где в этом вызове fnction появляется '$ image'? – RamRaider

+0

@DurimJusaj php..no logcat error – Tony

ответ

1
<?php 
    if($_SERVER['REQUEST_METHOD']=='POST'){ 

     if(!empty($_POST['listItems'])){ 

      $mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb"); 
      if($mysqli->connect_errno) echo "Failed to connect to MySQL";/* try not to reveal too much info! */ 

      /* The example you followed had this line! */ 
      $image = $_POST['image']; 

      $listItems = json_decode($_POST['listItems'], true); 

      /* This never gets called - should it? */ 
      $sql="SELECT id FROM staff_benefit ORDER BY id ASC"; 
      /* 
       This fetches ALL ids from the staff_benefit table 
       so which ID do you need? Iterating through the 
       recordset will effectively return the last one! 
      */ 

      $id=0; 



      /* 
       I assume that $id is supposed to get 
       the value from th above sql query??? 
      */  
      $res=$mysqli->query($sql); 
      while($rs=$res->fetch_object()) $id=$rs->id; 

      $path="$id.png"; 
      $actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path"; 


      /* Use only placeholders in your prepared statement */ 
      $sql="INSERT INTO `staff_benefit` (`type`, `amount`, `description`, `image`, `ts_id`) VALUES (?, ?, ?, ?, ?)"; 
      $stmt=$mysqli->prepare($sql); 


      /* Save the image to disk: I prefer to use the actual path for storing files */ 
      $pathelements=array(realpath($_SERVER['DOCUMENT_ROOT']), 'CRUD', 'PhotoUpload', '');/* empty entry adds trailing slash to path */ 
      $savepath = realpath(implode(DIRECTORY_SEPARATOR, $pathelements)) . "{$id}.png"; 

      $bytes=file_put_contents($savepath, base64_decode($image)); 
      if(!$bytes){ 
       echo 'Error saving image'; 
      } 

      if ($stmt && $bytes) { 
       foreach($listItems as $item){ 

        $stmt->bind_param('sssss', $item['type'], $item['amount'], $item['description'], $actualpath, $item['ts_id']); 
        $res=$stmt->execute(); 

        if(!$res) echo 'Query failed with code: '.$stmt->errno;/* Again, not too much info */ 
       } 
      } 
      $mysqli->close(); 
     } 
    } 
?> 
+0

спасибо, работа для меня :) – Tony

+0

привет, могу я вас здесь спросить? Почему, когда я clcik изображение в папке PhotoUpload, он сказал, что файл пуст? – Tony

+0

Что такое содержимое '$ _POST ['image']'? При попытке отладки таких вещей всегда полезно распечатывать переменные $ _POST, чтобы увидеть, какие поля у вас есть и какие значения! – RamRaider

Смежные вопросы