Android using Ion to upload file

时间:2016-07-11 19:08:48

标签: android ion

In my webservice i have simple upload function which tested by cUrl and its work fine without any problem, and I can upload file by cUrl successfully, now I want to upload file from android with Ion library, but i get this error:

unable to parse json

my code is:

Ion.with(ActivityAccountInfo.this)
                .load(MyApplication.getHostAddress() + "clientUploadPhoto")
                .uploadProgressHandler(new ProgressCallback() {
                    @Override
                    public void onProgress(long downloaded, long total) {
                        uploadMessage.setText("" + downloaded + " / " + total);
                    }
                })
                .setTimeout(60 * 60 * 1000)
                .setMultipartFile("userPhoto", "image/*", new File(photoPath))
                .asJsonObject()
                // run a callback on completion
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {
                        if (e != null) {

                        }
                    }
                });

and my web function:

Route::any('clientUploadPhoto', function () {
    $filename = Request()->file('userPhoto');
    $destinationPath = base_path() . '/upload/';
    $new_filename = time() . '_' . $filename->getClientOriginalName();
    Image::make($filename->getRealPath())->save($destinationPath . $new_filename);
});

1 个答案:

答案 0 :(得分:0)

在将位图设置为ImageView之后,其他解决方案解决了问题我使用此代码从中获取位图:

Bitmap bitmap = ((BitmapDrawable) user_avatar.getDrawable()).getBitmap();

然后我从那里创建Base64

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

现在我可以使用Ion上传该内容并将其转换为内部服务器:

php Laravel框架:

public function clientUploadPhoto()
{
    $image = Request::json()->get('file');
    $ext = Request::json()->get('ext');

    file_put_contents( base_path() . '/upload/'.time().$ext,base64_decode($image));
}