Uploading an image from Android (with Android Asynchronous Http Client) to laravel server

1k views Asked by At

i'm trying to upload an image via http post method from android device to laravel server. but Posting an image is not working, the post parameter (including image file) doesn't seem to be sent correctly.

i'm using Android Asynchronous Http Client (http://loopj.com/android-async-http/) to post an image from android. and here is the code :

Android :

RequestParams params = new RequestParams();
    params.put("id_personil", session.getUID());
    params.put("id_deskel", session.getDID());
    params.put("jenis", jenisLap.getSelectedItemPosition());
    params.put("judul", judul.getText().toString());
    params.put("lokasi", lokasi.getText().toString());
    params.put("uraian", uraian.getText().toString());
    try{
        for (int a =0; a<imageUrl.size();a++){
            params.put("pic[]", new File(Environment.getExternalStorageDirectory().getPath()+imageUrl.get(0)));
        }
    }catch(FileNotFoundException e){e.printStackTrace();}

    AsyncHttpClient client = new AsyncHttpClient();
    client.post("http://10.0.3.2:8888/api/v1/lapgiat", params, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            ShowAlert(response.toString(), "text");
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            super.onFailure(statusCode, headers, throwable, errorResponse);
            ShowAlert("Error", "error");
        }
    });

Laravel

if(Request::has('pic')){
        $files = Input::file('pic');
        //dd($files);
        $det_pic = [];
        foreach ($files as $file) {
            $filename = rand(11111,99999).'.'.$file->getClientOriginalExtension();
            $file->move('uploads', $filename);
            $det_pic[] = ['id_lapgiat'=>$id, 'file'=>$filename];
        }
        DB::table('bah_det_lapgiat_photo')->insert($det_pic);
        $output['has picture'] = true;
    }

can anyone help me?

1

There are 1 answers

0
viswanath608 On

Check using cURL or POSTMAN client and see if it's working there. If not, you can use this sample code for laravel.

//Checks if request has file or not
    if ($request->hasFile('pic')) {
//checks if file is uploaded or not
            if ($request->file('pic')->isValid()) {
                $extension = $request->file('pic')->getClientOriginalExtension();
                $imageName = str_random(60);
                $request->file('pic')->move(base_path() . 'file/save/location', $imageName.".".$extension);
                }
    }