在iPhone的 Safari上无法下载文件,但在Chrome上可以

移动开发 2026-07-12

我在为在 iPhone Safari 下载文件找解决方案时遇到了困难。

我分享的代码是我应用中的当前函数。它在 Google Chrome 上能正确下载,但在 Safari 上却不起作用。

怎样修复,才能让文件在 Safari 上也能下载?

const downloadDocument = async (url) => {
  try {
    const response = await fetch(url)
    const blob = await response.blob()
    const blobUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = blobUrl
    link.target = '_blank'
    link.download = url.split('/').pop() || 'document'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    setTimeout(() => window.URL.revokeObjectURL(blobUrl), 100)
  } catch (error) {
    console.error('Error downloading document.:', error)
    window.open(url, '_blank', 'noopener,noreferrer')
  }
}

解决方案

据我所知,Safari会忽略blob/object URL上的 a[download]

最好的做法是通过服务器响应头进行下载。这样在所有浏览器中都能工作。

如果你掌控服务器,请通过以下方式返回文件:

  • Content-Disposition: attachment; filename="document.pdf"
  • Content-Type: application/pdf(正确的MIME类型应该能通过)
  • Optional: Content-Length

一些参考资料

最后,不要把它变成Blob,只要

const downloadDocument = (url) => {
  # must be triggered from a user action (tap/click)
  window.location.href = url;
};

Or:

const downloadDocument = (url) => {
  window.open(url, '_self'); # iOS behave better with _self
};
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章