简体   繁体   English

从url或文件系统读取文件到javascript中的变量

[英]read in a file from url or filesystem to variable in javascript

I am trying to read in a file from a file on my computer and store in in a variable. 我正在尝试从计算机上的文件中读取文件并存储在变量中。 I am currently trying: 我目前正在尝试:

var fr = new FileReader;

fr.onload = function() {

    //variable to hold file
    var data = fr.result;

    var c=document.getElementById("cvs");
    var ctx=c.getContext("2d");
    ctx.drawImage(img,0,0,200,180);
};

fr.readAsDataURL("encryptedImage");

this does not work. 这行不通。 I need to do this do i can decrypt an encrypted image on my file system. 我需要这样做,才能解密文件系统上的加密图像。 I have already turned of the security so my file system can be read from a browser. 我已经放弃了安全性,因此可以从浏览器读取我的文件系统。

any ideas? 有任何想法吗?

From here it looks like you want to load the local file by passing a String to readAsArrayBuffer(), but it exspects a blob or file object. 从这里看来,您想要通过将String传递给readAsArrayBuffer()来加载本地文件,但是它可以检测到Blob或文件对象。 The file can be loaded via the browsers file dialog. 可以通过浏览器文件对话框加载该文件。 Steps are : Select the file, load the file via fileReader asArrayBuffer or asDataURL or asBinaryString ... and manipulate or use the data in your code. 步骤是:选择文件,通过fileReader asArrayBuffer或asDataURL或asBinaryString ...加载文件,然后操作或使用代码中的数据。

For this example it creates an Image from the local file and draws it onto the canvas (if it's of correct mime type "image.*" however). 对于此示例,它从本地文件创建一个Image并将其绘制到画布上(如果它是正确的MIME类型,则为“ image。*”)。

I'm not sure what kind of encoding/decoding you want to apply. 我不确定您要应用哪种编码/解码。 But for custom manipulation of data I would recommend using ArrayBuffers and TypeArrays. 但是对于自定义的数据处理,我建议使用ArrayBuffers和TypeArrays。

The example with FileReader.readAsDataURL(): http://jsfiddle.net/uvmD7/ FileReader.readAsDataURL()的示例: http : //jsfiddle.net/uvmD7/

<body>
  <canvas id="cvs" width="200" height="200"></canvas>
  <input type="file" id="files" name="files[]" multiple />
</body>

And the script: 和脚本:

document.getElementById('files').addEventListener('change', handleFileSelect, false);

var fr = new FileReader();

function handleFileSelect(evt) {
    var files = evt.target.files;
    fr.readAsDataURL(files[0]);
};

fr.onload = function(evt) {
    // do sth with it
    var data = evt.target.result; //fr.result 
    img = new Image();
    img.src = data; 
    //  draw after load
    img.onload = function() {
       var c=document.getElementById("cvs");
       var ctx=c.getContext("2d");
       ctx.drawImage(img,0,0,200,180);      
    };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM