简体   繁体   中英

React-Native : Download Remote Image to local and use static url

I'm developing an app for Android using the React-Native, that uses the react-native-maps package.

In Marker Component(react-native-maps) there is prop called "image" which can be used only with local images. but in my case I need to render remote image Url

<Marker
  coordinate={marker.latlng}
  image={require('../images/pin.png')}
/>

The above code is working fine since the image is static but i need to render a remote image instead of pin.jpg So is there a way i could do like this.

  • Download the remote url to images folder.
  • Use the saved image uri in Marker Component.

This what i am trying to achieve - Code similar to below

let path_to_save_image = '../images/'
some_package.fetch('http://www.example.com/image/new_image.png', 
    path_to_save_image, {
    //some headers ..
    })
    .then((res) => {
    console.log('The file saved ')
    })


render (){
  return (
    <Marker
     coordinate={marker.latlng}
    image={require('../images/new_image.png')}
    />)
}

Is there a way i could do this?

I have tried creating custom marker but it is not working out. #issue

You can use react-native-fs and path as show below import RNFS from 'react-native-fs';

module.exports = {
  getFileName(name: string) {
    const FILE = Platform.OS === 'ios' ? '' : 'file://' ;
    return FILE + RNFS.DocumentDirectoryPath + '/' + name + '.png';
  },

  downloadAndGetImageUrl(name: string, source_url: string) {
    let fileName = this.getFileName(name);
    return RNFS.exists(fileName)
     .then(response => {
       if(response) {
         return {uri: fileName}
       }else {
         let destination_path = '/' + name + '.jpg';
         return RNFS.downloadFile({
           fromUrl: source_url,
           toFile: RNFS.DocumentDirectoryPath + destination_path
         }).promise.then(response => {
            return {uri: fileName}
         }).catch((error) => {
           return {uri:source_url}
        });
      }
    })
    .catch((error) => {
      return {uri: source_url}
    })
 },
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM