How to access the React upload Enable in the Laravel API?

Asked

Viewed 316 times

0

I have an app in React on, I have an option that the user can change his avatar, I am using the library ImagePicker and I have the API in Laravel.

I’m having trouble accessing the chosen image in the room I’m giving a request->file('avatar') but returns null I don’t know why, what I’m doing wrong ?

React Native

handleChoosePhoto = () => {
    const options = {
      title: "Escolher Foto",
      takePhotoButtonTitle: "Tirar Foto...",
      chooseFromLibraryButtonTitle: "Escolher da Galeria...",
      mediaType: "photo",
      storageOptions: {
        skipBackup: true,
        path: "images"
      }
    };
    ImagePicker.showImagePicker(options, response => {
      console.log(response);

      if (response.didCancel) {
        console.log("User cancelled image picker");
      } else if (response.error) {
        showMessage({
          message: "Foto de Perfil",
          description: response.error,
          type: "danger",
          floating: true,
          duration: 2850
        });
      } else {
        this.handleUploadPhoto(response);
      }
    });
  };

  handleUploadPhoto = async responseSource => {
    try {
      const id = this.props.user.id;
      const data = new FormData();

      const uriPart = responseSource.uri.split(".");
      const fileExtension = uriPart[uriPart.length - 1];

      data.append("avatar ", {
        uri: responseSource.uri,
        name: `avatar.${fileExtension}`,
        type: `image/${fileExtension}`
      });

      const response = await api.post(`user/dados/${id}/avatar`, {
        data
      });

      console.log(response.data);

      showMessage({
        message: "Perfil",
        description: "Dados actualizados com sucesso!",
        type: "success",
        floating: true,
        duration: 2850
      });
    } catch (error) {}
  };

Laravel API

$user = $request->user_id;

avatar = request->file('avatar');

return response()->json(['avatar' => $avatar]);

2 answers

2


I was able to solve, due to various research and several tests, I ended up discovering that the API was yes coming. were two problems.

1

I was sending the date fo formaData in the request body ie I was sending as json and not as Content-Type: Multipart/form-data

2

In the API I was waiting to receive the file with the avatar name I passed in the formData but after some tests I found that it was coming there asavatar_ changed and everything worked.

I’ll leave the code to help someone in the future.

try {
  const id = this.props.user.id;
  const data = new FormData();
  let filename = this.state.imageSource.split("/").pop();

  data.append("avatar ", {
    uri: this.state.imageSource,
    name: filename,
    type: "image/jpeg"
  });

  await api.post(URL, data);

} catch (error) {}

1

This variable api is an instance of Axios?

Try adding a header Content-Type: Multipart/form-data to your request. If you are using Xios would be like this:

const response = await api.post(`user/dados/${id}/avatar`, {
  data
}, {
  headers: {'Content-Type': 'multipart/form-data'}
});
  • yes api and an instance of Axios, I tried to add this and nothing I put in the api of the Laravel a $request->file('avatar') to check by the console if it caught but nothing returns null

Browser other questions tagged

You are not signed in. Login or sign up in order to post.