简体   繁体   中英

Send file via Post using new SDK Firefox Addon

I'm searching to send a zip file to a server using the "Request" class from the new Firefox SDK for addons. This is my code:

var Request = require("sdk/request").Request;
var file = new FileUtils.File(pathToZipFile);
Request({
   url: serverURL,
   content: file,
   onComplete: function (response) {
       for (var headerName in response.headers) {
          console.log(headerName + " : " + response.headers[headerName]);
       }
       console.log("Response " + response.text );
    }
}).post();

But the error is:

[Exception... "Component returned failure code: 0x80520009 (NS_ERROR_FILE_INVALID_PATH) [nsILocalFile.target]" nsresult: "0x80520009 (NS_ERROR_FILE_INVALID_PATH)" location: "JS frame :: resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/commonjs/sdk/querystring.js :: stringify/< :: line 70" data: no]

I have tried to do some checks and:

  1. The server is on and receives normal GET and POST without files
  2. The zip file is present and the path is right

Do you see any errors? Thanks a lot

The only way to do it with the Request module is to base a base64 encoded string to the content key. If you don't use this, then you can send data such as a Blob or DOMFile ( new File() ) instance.

But as we see in the SDK code, the request module sends the data variable on request (if its not a HEAD or GET request).

https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/request.js#L110

The data var is made by running stringify on anything passed to the content key: https://github.com/mozilla/addon-sdk/blob/master/lib/sdk/request.js#L76

Stringify makes it a string: https://github.com/mozilla/addon-sdk/blob/f5fab7b242121dccfa4e55ac80489899bb9f2a41/lib/sdk/querystring.js#L30

So you have to send base64 encoded string. Or a binary string. Which sucks.

You can use the sdk/io module to read the file as an ArrayBuffer and then turn that ArrayBuffer into a base64 string or binary string.

This shows how to get a binary string: https://stackoverflow.com/a/16365505/1828637

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM