在 Google Chrome 扩展程序中上传文件 [英] Upload a File in a Google Chrome Extension

查看:118
本文介绍了在 Google Chrome 扩展程序中上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Chrome 编写一个扩展程序,我需要从用户当前所在的页面上传一个文件到我的服务器进行处理,但我不知道如何上传文件.我考虑过将链接传递给服务器并让服务器下载文件,但是如果站点需要身份验证,这将不起作用.是否可以通过 Chrome 扩展程序将文件上传到我的服务器?

解决方案

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

使用了以下方法:

  1. 文件下载:例如,获取 元素的 src 属性.
  2. 从缓存中获取文件 - 使用

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

    polyfill 的源代码可在 https://gist.github.com/Rob--W/8b5addd84c0d36aba64

    清单文件:

    <代码>{"name": "Rob W - 演示:抓取图片和发布数据","版本": "1.0",清单版本":2,内容脚本":[{"匹配": ["http://*/*", "https://*/*"],"js": ["contentscript.js"]}],背景": {脚本":[background.js"]},"权限": ["http://*/*", "https://*/*"]}

    相关文档

    I'm writing an extension for Chrome, and I need to upload a file from the page the user is currently on to my server to be processed, I cannot figure out how to upload the file though. I considered just passing the link to the server and having the server download the file, however if the site requires authentication this will not work. Is it possible to upload a file via a Chrome extension to my server?

    解决方案

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

    The following approach 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 of the image, Crypto-JS: MD5 can be used. Example (where xhr is the XMLHttpRequest object with responseType set to arraybuffer, see Worker 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 to transmit multipart/form-data forms. That's why I've written a polyfill for it. This code has to be included 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

    这篇关于在 Google Chrome 扩展程序中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆