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

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

问题描述

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

解决方案

我最近开发了一个Chrome扩展,然后将它发送到服务器。



使用以下方法:


  1. 文件下载:例如,获取< img> 元素的 src 属性。 / li>
  2. 从缓存中获取文件 - 使用 XMLHttpRequest

  3. 使用 Web Worker 处理上传。

注意,要取得可以使用 Crypto-JS:MD5 图像。示例(其中 xhr XMLHttpRequest 对象,其中 responseType 集合至 arraybuffer ,请参阅Worker demo):

  var md5sum =加密。 MD5(new Uint8Array(xhr.response)); 



完整示例



内容脚本



  //示例:抓取第一个< img>从文档中如果存在。 
var img = document.images [0];
if(img){
//发送图像的目标:
chrome.runtime.sendMessage({method:'postUrl',url:img.src});

$ c


$ b

后台脚本(带有Worker)



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



Web Worker



  //定义Web工作者的FormData对象:
importScripts('xhr2-FormData.js')

//注意:在Web工作者中,全局对象被称为self而不是window
self.onmessage = function(event){
var resourceUrl = event.data; //从背景页面
var xhr = new XMLHttpRequest();
xhr.open('GET',resourceUrl,true);

//响应类型arraybuffer - XMLHttpRequest 2
xhr.responseType ='arraybuffer';
xhr.onload = function(e){
if(xhr.status == 200){
nextStep(xhr.response);
}
};
xhr.send();
};
函数nextStep(arrayBuffer){
var xhr = new XMLHttpRequest();
//为Web工作人员使用FormData polyfill!
var fd = new FormData();
fd.append('server-method','upload');

//原生的FormData.append方法只需要Blob,文件或字符串
// Web工作者的FormData也可以处理数组缓冲区
fd.append('文件',arrayBuffer);

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

//将表单发送到服务器
xhr.send(fd);
};



Web工作者的FormData POLYFILL



Web工作人员本身不支持 FormData 对象,用于传输 multipart / form-data 表单。这就是为什么我为它写了一个polyfill。必须使用 importScripts('xhr2- FormData.js')



填充的源代码可在 https://gist.github.com/Rob--W/8b5adedd84c0d36aba64


$ b

清单文件:



  {
name:Rob W - 演示:刮图像和发布数据,
版本:1.0,
manifest_version:2,
content_scripts:[
{
matches:[http:// * / *,https:// * / *],
js:[contentscript.js]
}
],
background:{
scripts:[background.js]
},
permissions:[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天全站免登陆