0

How should I upload my pictures to laravel server using fetch method in react native? I am using react-native-image-picker in my react native project and follow that package https://aboutreact.com/example-of-image-picker-in-react-native/ and my response is like that

base64 ->  undefined
 LOG  uri ->  file:///data/user/0/proj_name/cache/rn_image_picker_lib_temp_e100eb14-7efc-4aee-aea9-dc9d05a61b51.jpg
 LOG  width ->  300
 LOG  height ->  400
 LOG  fileSize ->  13813
 LOG  type ->  image/jpeg
 LOG  fileName ->  rn_image_picker_lib_temp_e100eb14-7efc-4aee-aea9-dc9d05a61b51.jpg 

How I should upload that picture to my laravel back end with fetch method

2 Answers2

0

You can use this sample code in the backend, if your image form field name is "image" and you have a folder named "images" in storage. Your jpeg image will be saved in this directory.


    $imageData = $request->image;  // Your base64 encoded
    $fileName = str_random(10) . '.jpg';

    $imageData = str_replace('data:image/jpeg;base64,', '', $imageData);
    $imageData = str_replace(' ', '+', $imageData);

    \File::put(storage_path(). '/images/' . $fileName, base64_decode($imageData));

Arash
  • 304
  • 2
  • 10
-1

There is the One better way Convert the file in FormData format. you already getting the uri, type, and fileName, so Just store in an Object Like given below. you can hardcore that Image Name as well.

image: {
     name: IMage Name,
     type: ImageType,
     uri: imagePath
},

Before sending to the Database through API's Just Create The FormData like this and Append that Image object into it and send that formdata to server.

const formData = new FormData();
formData.append('profile_pic', state.image);

Now you can send This formData to the Backend.

Vivekajee
  • 21
  • 2
  • 11
  • I imagine they're going to need more information on how to accomplish this. Can you provide more detailed instructions or, ideally, sample code for how to accomplish this? Take a look at [@Arash's answer](https://stackoverflow.com/a/68565981/3025856) as a good example of how to answer questions. – Jeremy Caney Jul 28 '21 at 19:28
  • yes sure. as already he is getting the uri, type, and fileName, just he need to store these 3 things in the separate variables like and object image: { name:ImageName, type: imageType, uri: imageURI } and create the FormData Variable const formData = new FormData(); and append that image Object in formData formData.append('API Parameter Name', state.image); – Vivekajee Jul 28 '21 at 19:58
  • @JeremyCaney I hope the concept is clear Now! – Vivekajee Jul 28 '21 at 20:14