Sakshi
Sakshi

Reputation: 73

Convert uri to file react native js

enter image description here

Above is the request that I am trying to make in react native. But I have URI How shall I convert this to a file while sending to backend(PHP) server

This's my data to be sent in body:

 const profileImageToBeSentToUpdate = {
                     data: {
                         id: authContext.user.id,
                         token: authContext.user.oauth_token.access_token,
                        profile_image: source.uri //Need help here, need to convert uri to file in order to send to php
                     },
                     type: 'POST',
                     url: 'update_profile_image',
                    success: profileImageUpdateSuccess,
                     error: profileImageUpdateError
                 };
                 authContext.setLoader();
                 console.log('***********profile data binded: ', profileImageToBeSentToUpdate);
                 NetworkAdaptation.postData(profileImageToBeSentToUpdate);

Now, backend (PHP) wants file format, I have URI format in react

Upvotes: 0

Views: 9847

Answers (3)

Sakshi
Sakshi

Reputation: 73

I used image picker and from imageResponse during showImagePicker method got the following details and used it in data to send

profile_image: { uri: imageResponse.uri, name: imageResponse.fileName, type: imageResponse.type }

Upvotes: 0

Max
Max

Reputation: 4739

use rn-fetch-blob

import { Platform } from 'react-native';


const postImage = (localImageUri, remoteUrl) =>
    RNFetchBlob.fetch(
        'POST',
        remoteUrl,
        { 'Content-Type': 'multipart/form-data' },
        [
            {
                name: 'myimage',
                filename: 'myimage',
                type: 'image/jpeg',
                data: RNFetchBlob.wrap(Platform.OS === 'ios' ? localImageUri.replace('file://', '') : localImageUri),
            },
        ],
    ).then(response => {
        // do something
    }).catch(error => {
        // do something
    });

Upvotes: 1

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

React and React Native have no idea about what file system is. So they cannot make a file. A workaround could be download a new file by using this code:

downloadprofileImageFile = () => {
  const element = document.createElement("a");
  const file = new Blob([source.uri], {type: 'text/plain'});
  element.href = URL.createObjectURL(file);
  element.download = "profile_image.txt";
  document.body.appendChild(element);
  element.click();
}

Then, pass the file to your profileImageToBeSentToUpdate function.

Upvotes: 1

Related Questions