Djellal Mohamed Aniss
Djellal Mohamed Aniss

Reputation: 1743

sending a picture from my react native app to my laravel API with axios

i want to send a picture from my react native app to my laravel backend , for that am retrieving the picture URI and send a picture object using axios with others string data but the post request fails . knowing that when i send a post request without a picture , everything works fine .

EDIT : i have commented all the code on the if statement of my laravel function and changed it to a simple affectation to my $picture variable : $picture = "picture" , but the product is not added ! which means that the request is not even sended from my react app when i provide a picture .

my react native function :

    const config = { headers: { "Content-Type": "multipart/form-data" } };
    // appending some string data ...
    data.append("position", JSON.stringify(position));
    // checking if the user took a picture ..
    if (this.state.uri !== null) {
      let filename = this.state.uri.split("/").pop();
      data.append("picture", {
        uri: this.state.uri,
        name: filename,
        type: "image"
      });
    } else {
      data.append("picture", null);
    }
    // sending the request with axios to my backend ..
    const response = axios.post("product/create", data, config);

my laravel function :

   $user_id = $this->retrieveIdByToken($request->token);
    $picture = null;
    if ($request->hasFile("picture")){
        $picture = $request->file("picture")->getFilename() . "_" . $user_id . "." . $request->file("picture")->extension();
        Storage::putFileAs(
            '/public/products/pictures/', $request->file('picture'),$picture
        );
    }
    $product = Product::create([
        'user_id' => $user_id,
        'price' => $request->price,
        'position' => json_decode(json_encode($request->position)),
        'category_id' => $request->category_id,
        'name' => $request->name,
        'description' => $request->description,
        'caracteristics' => json_decode(json_encode($request->caracteristics)),
        'image' => $picture
        ]);

Upvotes: 0

Views: 2032

Answers (2)

Usama Shahid
Usama Shahid

Reputation: 865

Use RNFetchBlob library.

How it works,

Use Image Picker and save the image in state and then, use this code 10.0.3.2 is for genymotion, replace it if using real device

 RNFetchBlob.fetch('POST', 'http://10.0.3.2:8000/api/uploadImage', {
    Authorization : "Bearer access-token",
    otherHeader : "foo",
    'Content-Type' : 'multipart/form-data',
    'Accept':'application/json',
  }, [
     { name : 'image1', filename : 'avatar.png', data: this.state.image1},
    ]).then((response) => response.json())
  .then((responseJson) => {

    alert(JSON.stringify(responseJson));

  }).catch((err) => {
    alert(err)
  })

In Laravel, YOUR API,

Route::post('upload','ReactController@save');

YOUR CONTROLLER

public function save(Request $req){
$destinationPath = public_path('/upload');
            $image1=$request->file('image1');
            $_image1 = rand().'.'.$image1->getClientOriginalExtension();
            $image1->move($destinationPath, $_image1);

$info = new Upload;
$info->image = $_image1;
$info->save();

return json_encode("Successfully Saved");
}

Upvotes: 1

Djellal Mohamed Aniss
Djellal Mohamed Aniss

Reputation: 1743

i found out the solution , first i do not need to give axios a configuration , and the second one is that the type most be image/jpeg

Upvotes: 0

Related Questions