【问题标题】:Inserting a file input as an img in the DOM在 DOM 中将文件输入作为 img 插入
【发布时间】:2012-07-27 08:54:33
【问题描述】:

两部分问题...

基本上,在一天结束时,我想要一个file <input> 并让用户从他们的文件系统中选择一个图片文件。然后我想在页面上的 img 标签中显示它。我稍后需要处理它,所以我知道data: 不是要走的路,看起来它离开了blob:,我无法用我的googlefu 弄清楚它是X 起源还是不是。

那么blob: 是否被视为 X 起源?如果我有一个<img>@src 作为blob: URI,我可以使用getImageData() 吗?

如果是这样,那么您如何进行这一切?我想如果有人知道怎么做,那可能很简单,但我的 googlefu 又让我失望了……

所以:

  • blob: X-origin?
  • 如果不是,如何从file<input> 的内容中导出blob: URI?

【问题讨论】:

  • 对不起,我发布了一个我很少回答的问题。那么,blob 真的很重要吗?你想用那个图像做什么?上传?显示?
  • 我相信文件是一个 blob。试试URL.createObjectURL(input.files[0])

标签: javascript html blob same-origin-policy


【解决方案1】:

使用URL.createObjectURLFileBlob 对象生成blob:-URI:

基本演示:http://jsfiddle.net/HGXDT/

​<input type="file" id="file">​​​​​​​​​​​​​​<img id="preview">​​​​​​​​​​​​​​

window.URL = window.URL || window.webkitURL || window.mozURL;
document.getElementById('file')​.onchange = function() {
    var url = URL.createObjectURL(this.files[0]);
    console.log(url);
    document.getElementById('preview').src = url;
};​

检查脚本是否受同源策略影响的代码(答案:没有)。 (实际上,页面本身不受影响,因为它创建了blob:-URI,但其他页面无法在画布上绘制blob: URI并使用它):
http://jsfiddle.net/HGXDT/1/

<input type="file" id="file">
<img id="preview">
<canvas id="canvas"></canvas>
​
window.URL = window.URL || window.webkitURL || window.mozURL;
document.getElementById('file').onchange = function() {
    var url = URL.createObjectURL(this.files[0]);
    console.log(url);
    
    var img = document.getElementById('preview');
    canvasSOPTest(img, url);
};
// See console. SOP error has to show up
canvasSOPTest(new Image(), 'http://stackoverflow.com/favicon.ico?'+new Date());

function canvasSOPTest(img, url) {
    // Same Origin Policy check
    img.onload = function() {
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        console.log('Painting image...');
        ctx.drawImage(img, 0, 0);
        console.log('Attempting to get image data');
        try {
            ctx.getImageData(0, 0, canvas.width, canvas.height);
            console.log('Success! No errors');
        } catch (e) {
            console.log(e);
        }
    };
    img.src = url;
}

【讨论】:

    【解决方案2】:

    您想要的是使用 HTML5 File Api 显示图像,然后上传该图像还是其他方式?

    这是如何使用 File Api 预览图像的一个很好的例子。

    http://html5demos.com/file-api/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多