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

基本的に、問題はorが正しくないvar oBlob = Cc["@mozilla.org/files/file;1"].createInstance(Ci.nsIDOMFile, [oFileBody], { type: "text/xml"});ためです。nsIDOMFile は nsIDOMBlob から継承されていることに注意してください。"@mozilla.org/files/file;1"Ci.nsIDOMFile

誰が何をすべきか知っていますか?

本当にありがとう。

4

1 に答える 1

6

Let's cheat a little to answer this:

  • JS Code Modules actually have Blob and File, while SDK modules do not :(
  • Cu.import() will return the full global of a code module, incl. Blob.
  • Knowing that, we can just get a valid Blob by importing a known module, such as Services.jsm

Complete, tested example, based on your code:

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 に答える