Chrome扩展程序:如何将文件保存在磁盘上 [英] Chrome extension: How to save a file on disk

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

问题描述

我目前正在为Google Chrome创建一个扩展程序,可以将所有图像或链接保存到硬盘上的图像。

I'm currently creating an extension for google chrome which can save all images or links to images on the harddrive.

问题是我不知道使用JS或Google Chrome扩展API保存磁盘上的文件。

The problem is I don't know how to save file on disk with JS or with Google Chrome Extension API.

有没有想法?

Have you got an idea ?

推荐答案

您可以使用 HTML5 FileSystem功能使用下载 API写入磁盘。这是将文件下载到磁盘的唯一方法,它是有限的。

You can use HTML5 FileSystem features to write to disk using the Download API. That is the only way to download files to disk and it is limited.

你可以看看NPAPI插件。另一种做你需要的方法是通过XHR POST发送一个请求到外部网站,然后通过另一个GET请求来检索返回的文件,这将显示为一个保存文件对话框。

You could take a look at NPAPI plugin. Another way to do what you need is simply send a request to an external website via XHR POST and then another GET request to retrieve the file back which will appear as a save file dialog.

例如,对于我的浏览器扩展程序我的环聊,我创建了一个实用程序以供下载将HTML5 Canvas中的照片直接发送到磁盘。你可以看看这里的代码 capture_gallery_downloader.js 这样做的代码是:

For example, for my browser extension My Hangouts I created a utility to download a photo from HTML5 Canvas directly to disk. You can take a look at the code here capture_gallery_downloader.js the code that does that is:

var url = window.webkitURL || window.URL || window.mozURL || window.msURL;
var a = document.createElement('a');
a.download = 'MyHangouts-MomentCapture.jpg';
a.href = url.createObjectURL(dataURIToBlob(data.active, 'jpg'));
a.textContent = 'Click here to download!';
a.dataset.downloadurl = ['jpg', a.download, a.href].join(':');

如果您希望在HTML5中将URI转换为Blob的实现方式是我做到的:

If you would like the implementation of converting a URI to a Blob in HTML5 here is how I did it:

/**
 * Converts the Data Image URI to a Blob.
 *
 * @param {string} dataURI base64 data image URI.
 * @param {string} mimetype the image mimetype.
 */
var dataURIToBlob = function(dataURI, mimetype) {
  var BASE64_MARKER = ';base64,';
  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  var base64 = dataURI.substring(base64Index);
  var raw = window.atob(base64);
  var rawLength = raw.length;
  var uInt8Array = new Uint8Array(rawLength);

  for (var i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  var bb = new this.BlobBuilder();
  bb.append(uInt8Array.buffer);
  return bb.getBlob(mimetype);
};

然后在用户点击下载按钮后,它将使用下载HTML5 File API将blob URI下载到文件中。

Then after the user clicks on the download button, it will use the "download" HTML5 File API to download the blob URI into a file.

这篇关于Chrome扩展程序:如何将文件保存在磁盘上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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