自动下载然后上传Chrome扩展程序中的文件

时间:2014-01-27 01:10:34

标签: javascript html5 google-chrome file-upload google-chrome-extension

我正在编写一个Chrome扩展程序,可以自动从一个位置下载文件,然后将其上传到另一个位置。我已经弄清楚如何使用HTML5 Filesystem API来完成下载部分。但是,我不知道如何上传文件。

问题是上传必须通过使用“文件”输入元素的表单完成。我想告诉文件所在的表单(我可以从Filesystem API获取下载文件的位置)。但我无法想出一种以编程方式执行此操作的方法。

有什么想法吗?如果我能说清楚的话,请告诉我!

编辑:另一个选项是chrome.downloads扩展API

编辑:File API看起来很有前途(http://dev.w3.org/2006/webapi/FileAPI/)。我还发现这有用:https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

2 个答案:

答案 0 :(得分:2)

所以,这就是我最终实现它的方式。它是在Chrome扩展程序中完成的。我不认为在普通的浏览器脚本中是可能的,因为使用了canvas.toDataURL函数,如果下载的文件是跨源文件,则会抛出安全性异常。无论如何,这是我如何做到的简化版本。幸运的是,我正在下载和上传的文件是图像,所以我可以使用Image()类。

// load the image
var img = new Image();
img.src = "url to image";

// loaded
img.onload = function() {
    // convert the image into a data url
    var dataUrl = getImageDataUrl(this);

    var blob = dataUrlToBlob(dataUrl);

    // FormData will encapsulate the form, and understands blobs
    var formData = new FormData();

    // "image_name.png" can be whatever you want; it's what the
    // host will see as the filename for this image (the host server
    // that receives the posted form).  it doesn't have to match the
    // original filename, and can be arbitrary or not provided at all.
    formData.append("file", blob, "image_name.png");

    var request = new XMLHttpRequest();

    // upload
    request.open("POST", "url to form");
    request.send(formData);
};


// converts an image into a dataurl
function getImageDataUrl(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);


    // NOTE:  this will throw a cross-origin security exception
    // if not done in an extension and if the image is cross-origin
    return canvas.toDataURL("image/png");
}

// converts a dataurl into a blob
function dataUrlToBlob(dataUrl) {
    var binary = atob(dataUrl.split(',')[1]);
    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type: 'image/png'});
}

答案 1 :(得分:0)

我不知道是否存在这样的东西,但您可以使用Javascript动态创建表单,然后更新文件输入值并最终触发表单的提交事件。