在上传之前使用扩展名获取文件 [英] Grab file with chrome extension before upload

查看:168
本文介绍了在上传之前使用扩展名获取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用我的Chrome扩展,我想抓取一个文件(也许改变它),然后上传到网站。特别是从文件输入。
换个方式,如果我选择一个文件与输入[类型=文件]我想我的扩展中断任何提交并采取该文件。然后我的扩展将它的魔力应用到文件中,然后可以提交/上传文件。
我该如何处理这个问题?

文件路径出现问题。如果我抓住了文件输入的优势,由于HTML5标准和兼容性问题,它总是将实际路径更改为C:\ fakepath \。
我怎样才能访问文件呢?也许它是暂时保存在一些铬存储?

编辑:
嗯,我设法读取文件输入中选择的文件是这样的:

  var file; 
$('input [type = file]')。change(function(e){
file = e.target.files [0];
var reader = new FileReader();
reader.onload = function(event){
console.log(event.target.result); //包含文件数据
//也许更改数据并使用filewriter

};
reader.readAsDataURL(file);
};



<现在我想使用一个FileWriter写入e.target.files [0]



我遵循这个教程:
http://www.html5rocks.com/en/tutorials/file/filesystem/
,但我无法创建一个适当的FileWriter。

没有必要写在磁盘上的原始文件 - 可能甚至不可能 - 但我需要在相应的文件输入表单字段中更改用于上传的数据。 没有定义的API f或Chrome扩展程序来拦截请求的有效负载(正在进行中的工作)



这就是说,你可以使用内容脚本添加一个事件侦听器:


  1. 取消常规表单提交。
  2. 将文件读取为 ArrayBuffer 使用 <$ c
  3. 修改结果 ArrayBuffer 视图

  4. 创建一个 Blob
  5. 重建表单创建一个 FormData 实例,然后使用< a href =https://developer.mozilla.org/zh/DOM/XMLHttpRequest/FormData#append%28%29> .append(name,value [,filename]) 方法。

    注意:在下面的例子中,我没有包含表单重构方法。我只包括文件上传部分。有两种方法来重新构建表单:
    $ b $ ol

  6. 编写一个特定于表单的方法。
  7. 编写一个通用的表单解析方法,它处理无名/无效/未选中的元素。如果你想采取这个路线,看看

  8. 提交数据使用 XMLHttpRequest 。注意:如果您在Chrome扩展程序的上下文中运行此代码,请不要忘记在权限部分

下面是一个实现的例子:

$ $ p $ $ $ $ c $ //引用形式
var form = document.forms [ uploadForm];
form.addEventListener('submit',function(ev){
ev.preventDefault(); //取消提交

var fileInput = form.querySelector('input [type如果(!file)返回; //没有选择文件
var file = fileInput.files [0];
var fileReader = new FileReader();
fileReader.onload = function(){
var arraybuffer = fileReader.result;
//操作一个数组缓冲区,将其包装在视图中:
var view = new Uint8Array(arraybuffer);
view [0] = 0; //例如,将第一个字节更改为空字节

//创建一个适合使用的对象使用FormData
var blob = new Blob([view],{type:file.type});

//现在,表单重建+上传部分:
var formData = new FormData();
formData.append(fileInput.name,blob,file.name);
// ...处理表单的其余部分...

// N提交表单
var xhr = new XMLHttpRequest();
xhr.open('POST',form.action);
xhr.onload = function(){
//做些什么。例如:
alert(xhr.responseText);
};
xhr.onerror = function(){
console.log(xhr); //哦。错误。记录xhr对象用于调试

xhr.send(formData);
};
fileReader.readAsArrayBuffer(file);
});


using my chrome extension i would like to grab a file(and maybe change it) before it gets uploaded to a website. Particularly from file-inputs. Put another way if i select a file with an input[type=file] i want my chrome extension to interrupt any submit and take the file. Then my extension applies its magic to the file and after that the file may be submitted/uploaded. How can i approach this?

On problem occurs with the file path. If i grab the vaule of a file-input it always changes the actual path to " C:\fakepath\" due to HTML5 standard and compatibility issues. How can i access the file then? Maybe it is saved temporarily in some chrome storage?

EDIT: Well, i managed to read the file selected in the file input like this:

var file;
$('input[type=file]').change(function(e){
    file = e.target.files[0];
    var reader = new FileReader();      
    reader.onload = function (event) {
        console.log(event.target.result);  //contains the file data
        //maybe change data and use filewriter  

    };      
    reader.readAsDataURL(file);
};

Now i would like to use a FileWriter to write to e.target.files[0]

I followed this tutorial: http://www.html5rocks.com/en/tutorials/file/filesystem/ but i am not able to create a proper FileWriter.

It is not necessary to write to the original file on the disk - might not even possible - but i need to change the data that is used to upload in the corresponding file-input form field.

解决方案

There's no defined API for a Chrome extension to intercept the payload of a request (work in progress).

That being said, you can use a Content script to add an event listener which:

  1. Cancels the normal form submission.
  2. Reads the file as an ArrayBuffer using the FileReader API.
  3. Modify the resulting ArrayBuffer after wrapping it in a view.
  4. Create a Blob from the modified data.
  5. Reconstruct the form by creating a FormData instance, then use the .append(name, value[, filename]) method.
    Note: In the example below, I did not include the form reconstruction method. I only included the file upload part. There are two approaches to reconstruct the form:

    1. Write a method which is specific to your form.
    2. Write a general form-parsing method, which takes care of nameless/disabled/unchecked/... elements. If you want to take this route, have a look at the W3 specification for the Form submission algorithm.

  6. Submit the data using XMLHttpRequest. Note: If you're running this code in the context of your Chrome extension, don't forget to explicitly whitelist the URL at the permissions section in the manifest file.

Here's an example of the implementation:

// Reference to the form:
var form = document.forms["uploadForm"];
form.addEventListener('submit', function(ev) {
    ev.preventDefault(); // Cancel submission

    var fileInput = form.querySelector('input[type="file"]');
    var file = fileInput.files[0];
    if (!file) return; // No file selected

    var fileReader = new FileReader();
    fileReader.onload = function() {
        var arraybuffer = fileReader.result;
        // To manipulate an arraybuffer, wrap it in a view:
        var view = new Uint8Array(arraybuffer);
        view[0] = 0; // For example, change the first byte to a NULL-byte

        // Create an object which is suitable for use with FormData
        var blob = new Blob([view], {type: file.type});

        // Now, the form reconstruction + upload part:
        var formData = new FormData();
        formData.append(fileInput.name, blob, file.name);
        // ... handle remainder of the form ...

        // Now, submit the form
        var xhr = new XMLHttpRequest();
        xhr.open('POST', form.action);
        xhr.onload = function() {
            // Do something. For example:
            alert(xhr.responseText);
        };
        xhr.onerror = function() {
            console.log(xhr); // Aw. Error. Log xhr object for debugging
        }
        xhr.send(formData);
    };
    fileReader.readAsArrayBuffer(file);
});

这篇关于在上传之前使用扩展名获取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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