android如何使用Retrofit库发布ByteArray?

时间:2015-12-17 17:22:36

标签: android

public interface UploadImageService {

//send an image with params with Post
@Multipart
@POST("/image/upload_image.php")
void setUserImage(
        @QueryMap Map<String, String> params,
        @Part("pathImage") TypedFile file,          
        Callback<JsonElement> response);

}

我使用此代码发布Bitmap的Bytearray,但无法获得成功。哪个是将相机拍摄的图像发布到php服务器的最佳方式。

1 个答案:

答案 0 :(得分:1)

**Create an interface** 

public interface IMethodListener {

    @Headers({
            "Content-Type: application/json",
            "User-Agent: bytearray"
    })
    @POST("/postByte")
    public void postByte(@Body RequestLogin rObject, Callback<LoginModel> cb);

}

**Create Request and Response Model class**

public class RequestByteArray {
    public String base64Array;
    public RequestByteArray(String base64Array) {
        this.base64Array = base64Array;
    }
}

public class ByteArrayModel {
    public boolean Status;
    public String Message;
}

**Use below method in your activity or Fragment** 

 public void requestLoginApi(){
        showSpinner(true);
        RequestByteArray param = new RequestByteArray(byteArray.toString());
        IMethodListener api = adapter.create(IMethodListener.class);
        api.postByte(param, new Callback<LoginModel>() {
            @Override
            public void success(ByteArrayModel model, Response response) {
            }

            @Override
            public void failure(RetrofitError error) {
              }
        });
    }

**PHP function for converting base64 to row image file:**

  function base64_to_jpeg($base64_string, $output_file) {
      $ifp = fopen($output_file, "wb"); 

     $data = explode(',', $base64_string);

     fwrite($ifp, base64_decode($data[1])); 
     fclose($ifp); 

     return $output_file; 
   }