在Firefox插件中使用Blob

3

我一直在尝试让以下代码在Firefox插件中运行:

var oMyForm = new FormData();

oMyForm.append("username", "Groucho");
oMyForm.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"

// HTML file input user's choice...
oMyForm.append("userfile", fileInputElement.files[0]);

// JavaScript file-like object...
var oFileBody = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var oBlob = new Blob([oFileBody], { type: "text/xml"});

oMyForm.append("webmasterfile", oBlob);

var oReq = new XMLHttpRequest();
oReq.open("POST", "http://foo.com/submitform.php");
oReq.send(oMyForm);

来自https://developer.mozilla.org/zh-CN/docs/Web/Guide/Using_FormData_Objects?redirectlocale=en-US&redirectslug=Web%2FAPI%2FFormData%2FUsing_FormData_Objects

所以我知道我必须使用XPCOM,但是我找不到相应的东西。到目前为止,我找到了这个:

var oMyForm = Cc["@mozilla.org/files/formdata;1"].createInstance(Ci.nsIDOMFormData);

oMyForm.append("username", "Groucho");
oMyForm.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"

// JavaScript file-like object...
var oFileBody = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var oBlob = Cc["@mozilla.org/files/file;1"].createInstance(Ci.nsIDOMFile, [oFileBody], { type: "text/xml"});

oMyForm.append("webmasterfile", oBlob);

var oReq = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
oReq.open("POST", "http://localhost:3000");
oReq.send(oMyForm);

基本上问题出在 var oBlob = Cc["@mozilla.org/files/file;1"].createInstance(Ci.nsIDOMFile, [oFileBody], { type: "text/xml"}); 这一行,因为 "@mozilla.org/files/file;1" 或者 Ci.nsIDOMFile 不正确。注意 nsIDOMFile 继承自 nsIDOMBlob。

有人知道该怎么办吗?

非常感谢。

1个回答

6

让我们稍微作弊一下来回答这个问题:

  • JS Code Modules 实际上有 BlobFile,而 SDK 模块没有 :(
  • Cu.import() 将返回代码模块的完整全局对象,包括 Blob
  • 知道了这些,我们可以通过导入已知的模块(例如 Services.jsm)来获取有效的 Blob

基于您的代码的完整测试示例:

const {Cc, Ci, Cu} = require("chrome");
// This is the cheat ;)
const {Blob, File} = Cu.import("resource://gre/modules/Services.jsm", {});

var oMyForm = Cc["@mozilla.org/files/formdata;1"].createInstance(Ci.nsIDOMFormData);

oMyForm.append("username", "Groucho");
oMyForm.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"

// JavaScript file-like object...
var oFileBody = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var oBlob = Blob([oFileBody], { type: "text/xml"});

oMyForm.append("webmasterfile", oBlob, "myfile.html");

var oReq = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
oReq.open("POST", "http://example.org/");
oReq.send(oMyForm);

嘿,经过多年的使用和滥用该平台,我现在已经知道了很多。我偶然发现的作弊方法已经有一段时间了。其余的都是试错...哦,我经常查看源代码(http://mxr.mozilla.org/)! - nmaier
这太棒了!! - Noitidart
看起来有些东西改变了,你不能再像这样获取BlobFile了:http://stackoverflow.com/questions/27893399/how-do-i-use-the-dom-file-api-from-privileged-code - Noitidart

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接