wx.downloadFile filePath设计是否存在问题?
发布于 7 年前 作者 ezheng 8052 次浏览 来自 官方Issues

写在前面: 请注意,这是一个面向官方社区人员的问题,各位积极刷活跃的开发者们就不用回复了。

在这里的设计当中,如果填入 filePath,会直接将下载的文件写入到小程序文件系统中。但是这里的逻辑思路似乎存在一个问题。

正常的思路应该是__文件成功被获取才会写入存储路径__,也就是返回 2xx 的状态码,像 500, 404 403 这些异常状态应当被忽略。但是现在的思路是这个接口本身是只要请求成功,就无视状态码写入返回的body

很多服务器在请求的资源404时,不会返回空的body,而是返回一个网页。如 Ngnix 默认返回

<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
</html>
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->
<!-- a padding to disable MSIE and Chrome friendly error page -->

这就会导致小程序向文件系统中写入这个网页,而这并不是开发者本来想请求的文件,后续开发者再次本地尝试读取文件时如果不检测文件内容就会导致小程序运行异常。

目前的接口设计使得 filePath 这个参数失去了意义,开发者要么选择不使用这个参数,这样书写:

  wx.downloadFile({
    url: xxx,
    success: (res) => {
      if (res.statusCode === 200) {
        // 自行写入文件
      }
    },
  });

要么判断异常状态码自行删除

  wx.downloadFile({
    url: xxx,
        filePath: xxxx,
    success: (res) => {
      if (res.statusCode >= 400 ) {
        // 删除 filePath 的文件
      }
    },
  });

这就背离了 filePath 设计的初衷:为开发者提供简便。

希望的变更:

4xx 5xx 状态码不再默认写入 filePath

回到顶部