如何设置标头使用React Native和react-native-fs下载文件?

为了下载资产,在将react-native-fs与React Native一起使用时,需要设置一个Authorization标头。

在文档之后,标题设置如下:

  const options = {
    headers: {
      Authorization: `Bearer ${accessToken}`,},fromUrl: url,toFile: path,};

  // const permission = await insurePermissions();

  const task = RNFS.downloadFile(options);

它在iOS上运行完美,但是在Android上,使用运行Android 6、8、9或10的模拟器,则不会发送标头,因此服务器会返回错误的其他资产,因为用户不是被认证。

如何在Android中使用react-native-fs设置Authentication标头?

hudaichen0603 回答:如何设置标头使用React Native和react-native-fs下载文件?

此问题与其他React Native文件系统库一致。我改用Axios下载文件并与RNFS一起保存。

const fetchFile = async (accessToken,id) => {
  const dir = await getDirectory();
  await flushFileProofs();
  const baseUrl = 'https://example.com';
  const url = `${baseUrl}/images/${id}/download`;
  const fileName = `${id}-file.png`;
  const path = `${dir}/${fileName}`;

  const data = await axios.request({
    method: 'GET',url,headers: {
      Accept: '*/*',Authorization: `Bearer ${accessToken}`,},responseType: 'arraybuffer',})
    .then(response => Buffer.from(response.data,'binary').toString('base64'));

  await RNFS.writeFile(path,data,'base64');
  FileViewer.open(path);
};
本文链接:https://www.f2er.com/3169956.html

大家都在问