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/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。

有谁知道该怎么做?

谢谢一堆。

4

1 回答 1

6

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

  • JS 代码模块实际上有Bloband File,而 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);
于 2013-11-05T02:20:07.373 回答