我想将文件从表单传输到网络工作者。在 Chrome 中,我可以简单地使用此代码来传输 FileList-Object:
worker.postMessage(files: array_files);
但是使用 Firefox 我收到此错误:
Transfer file to webworker: DataCloneError: The object could not be cloned.
所以我尝试使用可传输对象的语法。像这样的吗?
var post = {files: array_files, file_ids: response.file_ids};
worker.postMessage(post, [post]);
但是我在 Chrome 中得到了这个
Uncaught DataCloneError: Failed to execute 'postMessage' on 'Worker': Value at index 0 does not have a transferable type.
仍然
DataCloneError: The object could not be cloned.
在火狐浏览器中。
将 FileList 传递给工作人员的正确方法是什么?
我不知道如何使用 postMessage 传递 File 对象,但至少我可以建议可传输对象不能以这种方式工作。可选的第二个参数是您希望传递的任何类型化数组的支持 ArrayBuffer 实例的数组。例如,假设您要发布的消息是结构化对象:
var message = {foo: 'abc', bar: new Uint8Array(...)};
worker.postMessage(message, [message.bar.buffer])
另请注意,将类型化数组作为可传输对象传递到另一个工作器/窗口会使发送的工作器/窗口无法访问传输的数组。
现在(2024年,可能还更早)
File
或Blob
物体今天就可以转移了。
(不起作用的是
fetch
的响应。因此要么应该使用blob()
提前读取数据,要么应该传递文件url。)