[ACCEPTED]-Upload a File in a Google Chrome Extension-upload

Accepted answer
Score: 43

I've recently developed a Chrome extension 9 which retrieves content from a page, and 8 sends it to the server.

The following approach 7 was used:

  1. File downloads: Get the src property of an <img> element, for example.
  2. Fetch the file from the Cache - use XMLHttpRequest from the background page.
  3. Use a Web Worker in the background page to handle the upload.

Side note, to take the checksum 6 of the image, Crypto-JS: MD5 can be used. Example (where 5 xhr is the XMLHttpRequest object with responseType set to arraybuffer, see Worker 4 demo):

var md5sum = Crypto.MD5( new Uint8Array(xhr.response) );

Full example

Content script

// Example: Grab the first <img> from the document if it exists.
var img = document.images[0];
if (img) {
    // Send the target of the image:
    chrome.runtime.sendMessage({method: 'postUrl', url: img.src});
}

Background script (with Worker)

chrome.runtime.onMessage.addListener(function(request) {
    if (request.method == 'postUrl') {
        var worker = new Worker('worker.js');
        worker.postMessage(request.url);
    }
});

Web Worker

// Define the FormData object for the Web worker:
importScripts('xhr2-FormData.js')

// Note: In a Web worker, the global object is called "self" instead of "window"
self.onmessage = function(event) {
    var resourceUrl = event.data;   // From the background page
    var xhr = new XMLHttpRequest();
    xhr.open('GET', resourceUrl, true);

    // Response type arraybuffer - XMLHttpRequest 2
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) {
        if (xhr.status == 200) {
            nextStep(xhr.response);
        }
    };
    xhr.send();
};
function nextStep(arrayBuffer) {
    var xhr = new XMLHttpRequest();
    // Using FormData polyfill for Web workers!
    var fd = new FormData();
    fd.append('server-method', 'upload');

    // The native FormData.append method ONLY takes Blobs, Files or strings
    // The FormData for Web workers polyfill can also deal with array buffers
    fd.append('file', arrayBuffer);

    xhr.open('POST', 'http://YOUR.DOMAIN.HERE/posturl.php', true);

    // Transmit the form to the server
    xhr.send(fd);
};

FormData for Web workers POLYFILL

Web workers do not natively support the FormData object, used 3 to transmit multipart/form-data forms. That's why I've written 2 a polyfill for it. This code has to be included 1 in the Web worker, using importScripts('xhr2-FormData.js').

The source code of the polyfill is available at https://gist.github.com/Rob--W/8b5adedd84c0d36aba64

Manifest file:

{
  "name": "Rob W - Demo: Scraping images and posting data",
  "version": "1.0",
  "manifest_version": 2,
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["contentscript.js"]
    }
   ],
   "background": {
       "scripts": ["background.js"]
   },
   "permissions": ["http://*/*", "https://*/*"]
}

Relevant documentation

Score: 1

The simplest solutions seems to be for your 9 extension to send the file's URI to your 8 server, and then your server-side code will 7 download it from the page into the server 6 and process it.

Create a server-side script 5 like http://mysite.com/process.php?uri=[file's 4 URI goes here] that will process the given 3 file. Use AJAX to call this URL (more info 2 at http://code.google.com/chrome/extensions/xhr.html ). The script will return the processed 1 file, which you could then use in your extension.

Score: 0

You should checkout the following:

chrome.extension.sendRequest() and 9 chrome.extension.onRequest()

You can read 8 more about them here: http://code.google.com/chrome/extensions/messaging.html

Basically you will 7 setup the page on the server to watch for 6 the Chrome extension, and once they connect 5 you will need to have a javascript that 4 will do the upload task for you.

I haven't 3 tested this out, but it may get you where 2 you need to be. Also you may want to read 1 the Long-lived connections section.

Goodluck

More Related questions