Unk*_*ech 28 upload google-chrome-extension
我正在为Chrome编写扩展程序,我需要将用户当前所在页面上的文件上传到我的服务器进行处理,但我无法弄清楚如何上传文件.我认为只是将链接传递给服务器并让服务器下载文件,但是如果站点需要身份验证,这将无法正常工作.是否可以通过Chrome扩展程序将文件上传到我的服务器?
Rob*_*b W 43
我最近开发了一个Chrome扩展程序,用于检索页面中的内容,然后将其发送到服务器.
使用了以下方法:
src
属性<img>
.XMLHttpRequest
从后台页面使用.注意,要采用图像的校验和,可以使用Crypto-JS:MD5.示例(设置xhr
为的XMLHttpRequest
对象在哪里,请参阅Worker演示):responseType
arraybuffer
var md5sum = Crypto.MD5( new Uint8Array(xhr.response) );
Run Code Online (Sandbox Code Playgroud)
// 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});
}
Run Code Online (Sandbox Code Playgroud)
chrome.runtime.onMessage.addListener(function(request) {
if (request.method == 'postUrl') {
var worker = new Worker('worker.js');
worker.postMessage(request.url);
}
});
Run Code Online (Sandbox Code Playgroud)
// 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);
};
Run Code Online (Sandbox Code Playgroud)
FormData
对于网络工作者POLYFILLWeb工作者本身不支持FormData
用于传输multipart/form-data
表单的对象.这就是为什么我为它写了一个polyfill.此代码必须包含在Web worker中importScripts('xhr2-FormData.js')
.
填料的源代码可在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://*/*"]
}
Run Code Online (Sandbox Code Playgroud)
chrome.runtime.onMessage
Google Chrome扩展程序XMLHttpRequest
2级 W3c规范FormData
(XHR2)MDN您应该检查以下内容:
chrome.extension.sendRequest() 和 chrome.extension.onRequest()
您可以在这里阅读有关它们的更多信息:http ://code.google.com/chrome/extensions/messaging.html
基本上,您将在服务器上设置页面以监视 Chrome 扩展程序,一旦它们连接,您将需要一个 javascript 来为您执行上传任务。
我还没有测试过这个,但它可能会让你到达你需要的地方。您还可能需要阅读长期连接部分。
祝你好运
归档时间: |
|
查看次数: |
16164 次 |
最近记录: |