在Google Chrome扩展程序中上传文件

时间:2010-11-04 03:40:10

标签: google-chrome-extension upload

我正在为Chrome编写扩展程序,我需要将用户当前所在页面上的文件上传到我的服务器进行处理,但我无法弄清楚如何上传文件。我考虑过只是将链接传递给服务器并让服务器下载文件,但是如果站点需要身份验证,这将无法正常工作。是否可以通过Chrome扩展程序将文件上传到我的服务器?

3 个答案:

答案 0 :(得分:42)

我最近开发了一个Chrome扩展程序,可以从页面中检索内容,然后将其发送到服务器。

使用了以下方法:

  1. 文件下载:例如,获取src元素的<img>属性。
  2. 从缓存中获取文件 - 从后台页面使用XMLHttpRequest
  3. 使用后台页面中的Web Worker来处理上传。
  4. 旁注,为了获取图像的校验和,可以使用Crypto-JS: MD5。示例(其中xhrXMLHttpRequest对象,responseType设置为arraybuffer,请参阅工作室演示):

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

    完整示例

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

    后台脚本(带工人)

    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适用于网络工作者POLYFILL

    Web workers本身不支持用于传输multipart/form-data表单的FormData对象。这就是为什么我为它写了一个polyfill。此代码必须使用importScripts('xhr2-FormData.js')包含在Web worker中。

    polyfill的源代码位于https://gist.github.com/Rob--W/8b5adedd84c0d36aba64

    清单文件:

    {
      "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://*/*"]
    }
    

    相关文件

答案 1 :(得分:1)

最简单的解决方案似乎是您的扩展程序将文件的URI发送到您的服务器,然后您的服务器端代码会将其从页面下载到服务器并进行处理。

创建一个服务器端脚本,如http://mysite.com/process.php?uri=[file的URI在这里],它将处理给定的文件。使用AJAX来调用此URL(http://code.google.com/chrome/extensions/xhr.html处的更多信息)。该脚本将返回已处理的文件,然后您可以在扩展程序中使用该文件。

答案 2 :(得分:0)

您应该检查以下内容:

chrome.extension.sendRequest()和chrome.extension.onRequest()

您可以在此处详细了解它们:http://code.google.com/chrome/extensions/messaging.html

基本上,您会在服务器上设置页面以观看Chrome扩展程序,一旦连接,您需要有一个javascript来为您执行上传任务。

我没有对此进行过测试,但它可能会让你到达你需要的地方。您也可以阅读长寿命连接部分。

古德勒克

相关问题