且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止 HTML 文件输入在使用 Android 的本机文件选择器时选择 Google Drive 中的文件

更新时间:2022-12-20 10:52:41

我不知道如何阻止文件选择器显示这些文件,我怀疑没有,但是如果您的代码可以很容易地检查将能够通过尝试读取将其发送到您的服务器.

I don't know a way to prevent the file picker to show these files, and I suspect there is none, but you can check quite easily if your code will be able to send it to your server by trying to read it.

我们可以尝试只读取第一个字节,而不是读取整个文件,方法是对 File 对象进行切片.然后阅读它,我们可以简单地调用它的 arrayBuffer() 方法 将返回一个 Promise,要么在文件有效时解析,要么在我们无法访问文件时拒绝:

Instead of reading the whole file, we can try to read only the first byte, by slicing the File object. Then to read it, we can simply call its arrayBuffer() method which will return a Promise, either resolving when the File is valid, or rejecting if we can't access the file:

const inp = document.querySelector('input');
inp.onchange = (evt) => {
  const file = inp.files[ 0 ];
  file.slice( 0, 1 ) // only the first byte
    .arrayBuffer() // try to read
    .then( () => {
      // success, we should be able to send that File
      console.log( 'should be fine' );
    } )
    .catch( (err) => {
      // error while reading
      console.log( 'failed to read' );
      inp.value = null; // remove invalid file?
    } );
};

<input type="file">

请注意,即使存储在磁盘上的文件也可能被用户修改,因为他们确实在您的网站上选择了它,在这种情况下,上传仍然会失败.要处理这种情况,您只需执行完全相同的测试即可.

Note that even Files stored on disk may be modified by the user since they did pick it in your website, in that case, the upload would still fail. To handle this case too, you'd just have to perform the same exact test.

还请注意,Blob.arrayBuffer() 是相当新的,可能需要一个 polyfill,它很容易在 Internet 上制作或找到.

Note also that Blob.arrayBuffer() is quite recent and may require a polyfill, which is easily made or found on the internet.