2016-11-05 5 views
0

Я пытаюсь загрузить изображение, используя Params.Загрузить изображение с помощью loopj android в slim framework REST api?

Android код:

POST данных на сервер

RequestParams params = new RequestParams(); 
      params.put("item_name", "Name of item"); 
      params.put("item_image", encodedImage); 

      MyRestClient.post(MainActivity.this, "item",params, new JsonHttpResponseHandler(){ 

       @Override 
       public void onSuccess(int statusCode, Header[] headers, JSONArray response) { 

        JSONArray jArr = response; 

        super.onSuccess(statusCode, headers, response); 
       } 

       @Override 
       public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { 

        String responseFromAPI = responseString; 

        super.onFailure(statusCode, headers, responseString, throwable); 
       } 

       @Override 
       public void onSuccess(int statusCode, Header[] headers, String responseString) { 

        String responseStr = responseString; 

        super.onSuccess(statusCode, headers, responseString); 
       } 


       @Override 
       public void onSuccess(int statusCode, Header[] headers, JSONObject response) { 

        JSONObject jObj = response; 

        super.onSuccess(statusCode, headers, response); 
       } 

       @Override 
       public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { 

        JSONObject jOBj = errorResponse; 

        super.onFailure(statusCode, headers, throwable, errorResponse); 
       } 

       @Override 
       public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) { 
        JSONArray jArr = errorResponse; 

        super.onFailure(statusCode, headers, throwable, errorResponse); 
       } 
      }); 

Bitmap Image Encode

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; 

     } 

Тонкий Framework Код:

$app->post('/image', function ($request, $response) { 


    $input   = $request->getParsedBody(); 

    $uploaded_image = $input['image_image'];  

    $path   = "/..../uploads/"."img-".date("Y-m-d-H-m-s").".jpg"; 

    if (file_put_contents($path, base64_decode($uploaded_image)) != false) 
    { 

     $sql = "INSERT INTO item (item_name, item_image) VALUES (:restaurant_name, :restaurant_image)"; 

     $sth = $this->db->prepare($sql); 
     $sth->bindParam("item_name", $input['item_name']);  
     $sth->bindParam("item_image", $input['item_image']); 

     $sth->execute(); 

     $input['id'] = $this->db->lastInsertId(); 

    } 


    return $this->response->withJson($input); 
}); 

Проблема:

Фотография должна быть загружена в соответствии с кодом и моим пониманием. Он не загружает изображение в нужную папку.

Я делаю что-то правильно или что-то пропустил?

ответ

2
<?php 
$app->post('/image', function ($request, $response) { 

    $files = $request->getUploadedFiles(); 
    $file = $files['image_image']; // uploaded file 

    $parameters = $request->getParams(); // Other POST params 

    $path = "/..../uploads/"."img-".date("Y-m-d-H-m-s").".jpg"; 

    if ($file->getError() === UPLOAD_ERR_OK) { 

     $file->moveTo($path); // Save file 

     // DB interactions here... 

     $sql = "INSERT INTO item (item_name, item_image) VALUES (:restaurant_name, :restaurant_image)"; 

     $sth = $this->db->prepare($sql); 
     $sth->bindParam("item_name", $input['item_name']);  
     $sth->bindParam("item_image", $input['item_image']); 

     // if statement is executed successfully, return id of the last inserted restaraunt 
     if ($sth->execute()) { 

      return $response->withJson($this->db->lastInsertId()); 

     } else { 

      // else throw exception - Slim will return 500 error 
      throw new \Exception('Failed to persist restaraunt'); 

     } 

    } else { 

     throw new \Exception('File upload error'); 

    } 

}); 
+0

Спасибо. Просто хотел сообщить, что изображение будет опубликовано вместе с другими полями. Это форма с опцией изображения. В этом случае напишу $ request-> getUploadedFiles(); ? – Abubaker

+0

Чтобы получить доступ к другим параметрам запроса, вы можете использовать '$ request-> geteParams()' (например, access '$ _POST'). Рассматривайте '$ request-> getUploadedFiles()' как доступ к '$ _FILES'. –

+0

Я хочу обновить свой интерфейс после получения либо успеха, либо неудачи в приведенном выше коде в коде Android (почтовый индекс клиента)? Могу ли я сохранить переменную флага или есть другой способ? – Abubaker