update: Finally I find out the reason myself, the reason is: actually I used Angular's ng-href at the same time, which prefix a unsafe
to the data url, I have to config the compiler service to waive that restriction like:
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
// Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
}
])
Which talks about here: Angular changes urls to "unsafe:" in extension page
所有
我想要做的是将图像作为dataURL读取并将其作为下载标记给它:
<input type='file' name='doc' />
<a href="#" download="data">Download</a>
<script>
var fileOBJ = $("input")[0]
.files[0];
var reader = new FileReader();
reader.onload = function(e){
$("a")[0].href=e.target.result;
}
reader.onerror = function(err){
console.log(err);
}
reader.readAsDataURL(fileOBJ);
</script>
下载总是失败。
但如果我使用<img>
代替<a>
,则可以显示图片。我不知道<a>
链接
答案 0 :(得分:1)
在链接上指定atrribute download
。像这样:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='file' name='doc' />
<a download="filename" href="#">Download</a>
<script>
$("input").change(function() {
var fileOBJ = $("input")[0]
.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$("a")[0].href = e.target.result;
// if you want to change the download filename
// $($("a")[0]).attr("download", "some other filename");
}
reader.onerror = function(err) {
console.log(err);
}
reader.readAsDataURL(fileOBJ);
})
</script>
&#13;
答案 1 :(得分:1)
如果选择了任何文件,则会尝试调用readAsDataURL
,这会引发错误。选择一些文件后使用此方法。
var reader = new FileReader();
reader.onload = function(e){
$("a")[0].href = e.target.result;
};
reader.onerror = function(err){
console.log(err);
};
$('#inpFile').on('change',function(){
reader.readAsDataURL(this.files[0]);
});