You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-native-blob-util iOS端下载文件无法自定义文件名如何解决?

解决iOS端自定义文件名问题

问题根源

你的代码存在两个核心问题导致iOS端文件名异常:

  • fileCache: true 会让iOS默认将文件存到临时目录,即便指定了ios.path也会被忽略
  • 手动保存时用了错误的编码格式:PDF是二进制文件,utf8编码会导致文件为空,base64编码需确保数据格式匹配

修复方案

方案1:直接指定最终路径写入

关闭fileCache,让iOS端直接将文件写入自定义路径,无需依赖临时文件:

export const downloadFile = async (url: string, fileName: string, description: string) => {
  const { config, android, ios, fs } = RNFetchBlob
  const mimeType = 'application/pdf'
  const date = new Date()
  const timestamp = Math.floor(date.getTime() + date.getSeconds() / 2)
  
  // 分别定义两端完整文件路径
  const iosFilePath = `${fs.dirs.DocumentDir}/${fileName}_${timestamp}.pdf`
  const androidFilePath = `${fs.dirs.DownloadDir}/${fileName}_${timestamp}.pdf`

  const options = {
    fileCache: false,
    addAndroidDownloads: {
      useDownloadManager: true,
      mediaScannable: true,
      notification: true,
      path: androidFilePath,
      description,
      mimeType
    },
    ios: {
      path: iosFilePath,
      description,
      mimeType
    }
  }

  await config(options)
    .fetch('GET', url)
    .then((res) => {
      if (Platform.OS === 'ios') {
        ios.openDocument(iosFilePath)
      } else {
        android.actionViewIntent(res.path(), mimeType)
      }
    })
}

方案2:下载后复制临时文件到自定义路径

如果需要保留fileCache: true,可在下载完成后将临时文件复制到目标路径:

export const downloadFile = async (url: string, fileName: string, description: string) => {
  const { config, android, ios, fs } = RNFetchBlob
  const mimeType = 'application/pdf'
  const date = new Date()
  const timestamp = Math.floor(date.getTime() + date.getSeconds() / 2)
  const iosTargetPath = `${fs.dirs.DocumentDir}/${fileName}_${timestamp}.pdf`

  const options = {
    fileCache: true,
    addAndroidDownloads: {
      useDownloadManager: true,
      mediaScannable: true,
      notification: true,
      path: `${fs.dirs.DownloadDir}/${fileName}_${timestamp}.pdf`,
      description,
      mimeType
    },
    ios: {
      description,
      mimeType
    },
    appendExt: 'pdf'
  }

  await config(options)
    .fetch('GET', url)
    .then(async (res) => {
      if (Platform.OS === 'ios') {
        // 复制临时文件到自定义路径
        await fs.cp(res.path(), iosTargetPath)
        // 可选:删除临时文件释放空间
        await fs.unlink(res.path())
        ios.openDocument(iosTargetPath)
      } else {
        android.actionViewIntent(res.path(), mimeType)
      }
    })
}

手动保存的编码修正

如果必须使用fs.writeFile,需用base64编码写入(前提是请求配置指定responseType: 'base64',确保res.data为base64格式的二进制数据):

// 正确写法
fs.writeFile(iosTargetPath, res.data, 'base64')
  .then(() => ios.openDocument(iosTargetPath))

内容的提问来源于stack exchange,提问作者Jacki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:07:43