使用URL.createObjectURL
从File
或Blob
对象产生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;
}
对不起,我发布了一个aswner我很少有人没有回答你的问题。那么,blob真的很重要?你想用这个图像做什么?上传?显示? – devundef 2012-07-29 11:30:06
我相信一个文件是一个blob。尝试'URL.createObjectURL(input.files [0])'。 – pimvdb 2012-07-29 11:31:54
http://html5demos.com/file-api/也相当不错。 – haxxerz 2012-07-30 15:08:40