在firefox附加组件上使用Blob

时间:2013-11-05 01:18:47

标签: javascript firefox firefox-addon firefox-addon-sdk xpcom

试图让以下代码在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/en-US/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 个答案:

答案 0 :(得分:6)

让我们作弊来回答这个问题:

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

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

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);