JS FileReader无法正确读取文件

时间:2015-07-01 11:40:47

标签: javascript jquery html ruby-on-rails

我对JS非常基本但我需要完成一项任务,即改变图片选定部分的颜色。这已经在一个单页的html + js示例中做得很好,现在我需要更改Rails应用程序以使用它。

我的主要问题是在Rails应用程序中,页面上已经放置了一个图像(有很多图像,单独编辑),我无法让FileReader从中读取。

它抛出中间'if'的情况 - '这个浏览器似乎不......'这个案例真的意味着什么?我在这里找到了一个解释:Link但是我没理解。我可以将给定的图片加载到画布,但它仍然给我留言。哦,imgfile'类型是未定义的。为什么?...

以下代码并不代表我的整个代码。

  function loadImage() {
          var input, file, fr, img, x;

          if (typeof window.FileReader !== 'function') {
              write("The file API isn't supported on this browser yet.");
              return;
          }

          input = document.getElementById('imgfile');
          if (!input) {
              write("Um, couldn't find the imgfile element.");
          }
          else if (!input.files) {
              write("This browser doesn't seem to support the `files` property of file inputs.");
              x = document.getElementById('imgfile').type;
              write(x);
          }
          else if (!input.files[0]) {
              write("Please select a file before clicking 'Load'");
          }
          else {
              file = input.files[0];
              fr = new FileReader();
              fr.onload = createImage;
              fr.readAsDataURL(file);
          }
我根据糟糕的假设编辑了这篇文章。

2 个答案:

答案 0 :(得分:0)

FileReader应该从文件系统中读取文件。 你必须做下一个:

var img = new Image();
var canvas = document.createElement("canvas");
var ctx    = canvas.getContext('2d');
img.onload = function(){
  ctx.drawImage(this, 0, 0);
  ctx.toDataURL();  // <--- Here is your source of an image.
};
img.src = document.getElementById('imgfile').src;

不确定,为什么你需要阅读你已经拥有的网址的图像。

答案 1 :(得分:0)

我正在回答自己,因为我找到了问题的根源 - FileReader只能对用户上传的文件进行操作...

相关问题