我想转换"图像对象"到"文件对象"在客户端使用HTML5将文件上传到azure blob存储。
由于我使用AngularJs,我的计划是
我找到了许多使用FileReader将File对象转换为图像的示例,但我找不到相反的示例。
我听说使用客户端javascript将文件写入本地文件系统是不可能的,但我不需要存储文件,我只需要文件对象引用来上传文件
有什么方法可以解决这个问题吗?
答案 0 :(得分:4)
您可以使用fetch和FormData进行转换和上传。
next
对于您的情况,只需将 //load src and convert to a File instance object
//work for any type of src, not only image src.
//return a promise that resolves with a File instance
function srcToFile(src, fileName, mimeType){
return (fetch(src)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], fileName, {type:mimeType});})
);
}
//usage example: (works in Chrome and Firefox)
//convert src to File and upload to server php
srcToFile('/images/logo.png', 'new.png', 'image/png')
.then(function(file){
var fd = new FormData();
fd.append('file1', file);
return fetch('/upload.php', {method:'POST', body:fd});
})
.then(function(res){
return res.text();
})
.then(console.log)
.catch(console.error)
;
替换为 '/images/logo.png'
答案 1 :(得分:-2)
有一种方法可以通过File System API将文件保存到本地文件系统,但只有Chrome和Opera支持它。如果要将图像文件从File / Blob渲染为IMG标记,可以执行
img.src = URL.createObjectURL(myFileOrBlob);
这会将文件/ Blob转换为网址,该网址仅在您的浏览器中可用,并且看起来像
blob:http%3A//localhost/2ee59cd6-9220-429c-add9-05983645639e
完成图像使用后,通过执行
来释放内存是一件好事URL.revokeObjectURL(blobURL);
希望我能正确理解你并帮助你。