2013-11-05 17 views
3

一直試圖讓下面的代碼在Firefox工作附加:使用斑點在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繼承。

任何人都知道該怎麼辦?

謝謝你一堆。

回答

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

哇...你怎麼知道這個:|。謝謝! – s12chung

+0

呵呵,經過多年的使用和濫用平臺,我現在知道了很多。一段時間以前我偶然發現的作弊行爲。剩下的就是試驗性錯誤......哦,我仔細查看了[source](http://mxr.mozilla.org/)! – nmaier

+0

這是壯觀的! – Noitidart