我想让用户预览他们的图片看起来像div的背景。 我不想让他们将图像上传到我的服务器,而是将其存储在本地缓存中,并让Jquery抓住路径并将背景图像替换为用户选择的图像......
答案 0 :(得分:2)
您可以将图片转换为Data URI,并在预览图片时使用该图片。
答案 1 :(得分:1)
听起来像File API的理想用例。 File API仅需要[足够] HTML5支持。 (也就是说,jQuery也不是。)您现在可以编写代码并在Firefox和Chrome中进行测试:
http://www.caniuse.com/#feat=fileapi
对于移动用户,还有PhoneGap和其他第三方解决方案。
答案 2 :(得分:1)
不是跨浏览器:
document.getElementById('uploader').onchange = function(){
var file = document.getElementById('uploader').files[0];
if (!file.type.match(/image.*/)) {
// this file is not an image.
alert('File type not supported');
}
else{
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function(e) {
img.src = e.target.result;
delete this;
}
img.onload = function(e) {
//do your code
}
reader.readAsDataURL(file);
}
};
答案 3 :(得分:1)
这是我使用jQuery和HTML5 File API汇总的东西。在输入[type ='file']的更改时,它将尝试将图像加载为img标记的src。 File APi实际上将本地文件转换为DataURI,然后您可以将其作为src
提供