问题描述
我正在为 Chrome 编写一个扩展程序,我需要从用户当前所在的页面上传一个文件到我的服务器进行处理,但我不知道如何上传文件.我考虑过将链接传递给服务器并让服务器下载文件,但是如果站点需要身份验证,这将不起作用.是否可以通过 Chrome 扩展程序将文件上传到我的服务器?
我最近开发了一个 Chrome 扩展程序,它可以从页面中检索内容,并将其发送到服务器.
使用了以下方法:
- 文件下载:例如,获取
元素的
src
属性. - 从缓存中获取文件 - 使用
网络工作者本身不支持
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://*/*"]}
相关文档
- 消息传递
chrome.runtime.onMessage
XMLHttpRequest
2 级FormData
(XHR2)- ArrayBuffer 响应 (XHR2) (注意:arraybuffer 响应已被弃用,以支持类型化数组,polyfill 已更新以反映此更改)
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:
- File downloads: Get the
src
property of an<img>
element, for example. - Fetch the file from the Cache - use
XMLHttpRequest
from the background page. - 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 theXMLHttpRequest
object withresponseType
set toarraybuffer
, 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 POLYFILLWeb workers do not natively support the
FormData
object, used to transmitmultipart/form-data
forms. That's why I've written a polyfill for it. This code has to be included in the Web worker, usingimportScripts('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
- Message passing
chrome.runtime.onMessage
XMLHttpRequest
Level 2FormData
(XHR2)- ArrayBuffer responses (XHR2) (note: arraybuffer responses are deprecated in favor of typed arrays, the polyfill has been updated to reflect this change)
这篇关于在 Google Chrome 扩展程序中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!