RNFetchBlob 下载 iOS 版文件并更改其文件名

问题描述 投票:0回答:1

我使用库react-native-blob-util来下载文件并将其保存在手机内存中。它在 android 和 ios 上都运行良好。不过,我也希望给文件指定特定的文件名,在这里我遇到了问题,对于 android 来说它仍然可以很好地工作,但是对于 ios 我有文件“ReactNativeBlobUtilTmp_****”。如何将其更改为正常文件名?

export const downloadFile = async (url: string, fileName: string, description: string) => {
  const { config, android, ios, fs } = RNFetchBlob
  const mimeType = 'application/pdf'
  const downloadDir = Platform.OS === 'ios' ? fs.dirs.DocumentDir : fs.dirs.DownloadDir
  const date = new Date()
  const options = {
    fileCache: true,
    addAndroidDownloads: {
      //Related to the Android only
      useDownloadManager: true,
      mediaScannable: true,
      notification: true,
      path: `${downloadDir}/${fileName}_${Math.floor(date.getTime() + date.getSeconds() / 2)}.pdf`,
      description,
      mimeType
    },
    ios: {
      //Related to the IOS only
      path: `${downloadDir}/${fileName}_${Math.floor(date.getTime() + date.getSeconds() / 2)}`,
      description,
      mimeType
    },
    appendExt: 'pdf'
  }

  await config(options)
    .fetch('GET', url)
    .then((res) => {
      // to open file after download
      if (Platform.OS === 'ios') {
        ios.openDocument(res.data)
      } else {
        android.actionViewIntent(res.path(), mimeType)
      }
    })
}

enter image description here

编辑:我发现这可能是因为在ios上我需要将文件保存在某个地方,而这个奇怪的名称是从存储它的某个tmp位置获取的。尽管如此,它也不起作用,我将 if ios 条件修改为下面的代码,其中路径与我上面使用的路径是可变的。如果我将编码设置为base64,它根本不想保存,使用utf8它确实保存(或至少不会抛出错误),但文件是空的:

fs.writeFile(path, res.data, 'utf8')
.then(() => ios.openDocument(path)) 
react-native react-native-fetch-blob
1个回答
0
投票

我也有同样的问题。 截至目前,react-native-blob-util 版本

0.19.11
:

这里不存在您使用的

ios
字段,配置对象必须与
ReactNativeBlobUtilConfig
类型模式匹配。

要在 iOS 上为您的文件指定正确的名称并使用“ReactNativeBlobUtilTmp_****”完成,您只需在

path
 之外添加 
addAndroidDownloads

字段即可

另外,如果文件扩展名尚不存在,请不要忘记添加。

示例:

const downloadPath =
    Platform.OS === 'ios'
        ? `${ReactNativeBlobUtil.fs.dirs.DocumentDir}/${documentTitle}`
        : `${ReactNativeBlobUtil.fs.dirs.DownloadDir}/${documentTitle}`;

return ReactNativeBlobUtil.config({
    fileCache: true,
    addAndroidDownloads: {
        title: 'title',
        description: 'description',
        mime: 'application/pdf',
        useDownloadManager: true,
        mediaScannable: true,
        notification: true,
        path: `${downloadPath}.pdf`,
    },
    path: `${downloadPath}.pdf`,
})
© www.soinside.com 2019 - 2024. All rights reserved.