Home > Software engineering >  How to send React Native Camera captured image to Back-end Laravel?
How to send React Native Camera captured image to Back-end Laravel?

Time:11-07

I have captured an image with React Native (expo-app) and can't find a proper way to send it to backend, mostly 500 and 422 appears (422 at this example).

Here is how a image data looks

{"base64": null, "height": 820, "uri": "file:///var/mobile/Containers/Data/Application/792E2665-5063-4853-876E-3793568C7FCF/Library/Caches/ExponentExperienceData/%40anonymous%2Fexpo-app-27783a0c-0a97-44a6-be26-48d37639bb25/ImageManipulator/9FCEF372-7C90-484F-9028-7D4271F9978D.jpg", "width": 476}

Here is the axios request to the backend, a photo state contains the data of image like above

     const handleSubmit = async() => {
        const formData = new FormData();
        formData.append("photo", {
          uri: photo.uri,
          name: photo.uri.split('/').pop(),
          type: 'image/jpg'
      });
      
        await axios.post("/api/upload", {
            formData
          }, {
            headers: { "Content-Type": "multipart/form-data" },
          }).then(response => {
            console.log(response.data)
          })
      }

Here is the laravel side, it can't go through validation

public function store(Request $request)
{
    $validated = $request->validate([
        'photo' => 'required|mimes:jpg,png,jpeg'
    ]);

    return response()->json([
        'status' => 'successfuly executed',
    ]);
}

Here is the laravel err log of what was in the request, even though console logging in the front end right before sending request, an object of image exist.

{"formData": null}

I can't figure out how to upload or even get captured image to react back-end, any ideas?

CodePudding user response:

await axios.post("/api/upload", 
        formData
      , {
        headers: { "Content-Type": "multipart/form-data" },
      }).then(response => {
        console.log(response.data)
      })

remove brackets and try again

CodePudding user response:

This image URI - file:///var/mobile/Containers/Data/Application/792E2665-5063-4853-876E-3793568C7FCF/Library/Caches/ExponentExperienceData/%40anonymous%2Fexpo-app-27783a0c-0a97-44a6-be26-48d37639bb25/ImageManipulator/9FCEF372-7C90-484F-9028-7D4271F9978D.jpg is a reference to image data on device memory but not actually image data.

expo-image-picker returns base64 image data and you can upload them to your server.

  • Related