Hon*_*Yoo 6 javascript html5 image
我想在客户端使用HTML5将"图像对象"转换为"文件对象",以将文件上传到azure blob存储.
由于我使用的是AngularJs,我的计划是
我找到了许多使用FileReader将File对象转换为图像的示例,但我找不到相反的示例.
我听说使用客户端javascript将文件写入本地文件系统是不可能的,但我不需要存储文件,我只需要文件对象引用来上传文件.
有什么方法可以解决这个问题吗?
cui*_*ing 12
您可以使用 fetch 和 FormData 进行转换和上传。
//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)
;
Run Code Online (Sandbox Code Playgroud)
对于您的情况,只需替换'/images/logo.png'为imageObject.src