Как я могу загрузить файл с сервера в определенную папку в рабочей области кода моего проекта в среде реагирования?

У меня есть реактивный проект, ведь мне нужно иногда обновлять свои ресурсы, у меня есть папка «приложение/активы» в корне моего проекта рядом с app.js, я установил «реагировать-нативный-fetch-blob» для загрузки файла и также используя API своей файловой системы, чтобы записать его в папку «активы», но я не могу сохранить его в своей папке. Я могу использовать только «RNFetchBlob.fs.dirs.DocumentDir», который я не знаю, где он находится, и также я не могу использовать его в мой код, как я могу записать загруженный файл точно в папку «активы»? вот мой код:

import RNFetchBlob from 'rn-fetch-blob'

type Props = {};
export default class App extends Component<Props> {

  constructor(){
    super();
    this.state = {
        download : 'not yet'
    }
  }

  componentDidMount(){
    this._testDownload();
  }
  _testDownload = () => {
    RNFetchBlob.fetch('GET', 'https://www.gstatic.com/webp/gallery3/1.png', {
    Authorization : 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzIwMDY4MDEsInVpZCI6Mjk5LCJ1c2VybmFtZSI6Imd1ZXN0XzM5MjQ4NDUiLCJlbWFpbCI6IiIsInJvbGVzIjpbIlVTRVIiXX0.gQ_Gqehx3tcWYI0C5CGmpaTfT33t_TPCKbuIYYOqVBU',
    'Content-Type' : 'octet-stream',
    // more headers  ..
  })
  .then((res) => {
    let status = res.info().status;
    console.log('status' , status)
    if(status == 200) {

      // the conversion is done in native code
      let base64Str = res.base64()     
      RNFetchBlob.fs.writeFile(`${RNFetchBlob.fs.dirs.DocumentDir}/app/assets/1.png`, base64Str, 'base64')
              .then(()=>{
                console.log('here check')
              }).catch(err => console.log('err', err))      
    } else {
      // handle other status codes
    }
  })
  // Something went wrong:
  .catch((errorMessage, statusCode) => {
    // error handling
  })
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{this.state.download}</Text>
      </View>
    );
  }
}

person Pouya92    schedule 18.07.2019    source источник


Ответы (1)


Use this code for download image using RNFetchBlob 
more information visit 

https://www.npmjs.com/package/rn-fetch-blob?activeTab=depends

import RNFetchBlob from 'rn-fetch-blob'

type Props = {};
export default class App extends Component<Props> {

  constructor(){
    super();
    this.state = {
        download : ''
    }
  }

  componentDidMount(){
    this._testDownload();
  }
  _testDownload = () => {

        PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: "Storage",
            message: "This app would like to store some files on your phone"
          }
        )
          .then(() => {
            let dirs =
              `/storage/emulated/0/app/assets/`


              RNFetchBlob.config({
                path: dirs + '/1.png',
                fileCache: true
              })
                .fetch("GET",' https://www.gstatic.com/webp/gallery3/1.png', {})
                .then(res => {
                  console.log("res.data============================", res.data);

                })
                .catch(err => {
                  console.log("Error ", err);
                });
            }

          })


  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{this.state.download}</Text>
      </View>
    );
  }
}
person HAPPY BHALODIYA    schedule 26.08.2019