【问题标题】:Converting image object to File object, javascript将图像对象转换为文件对象,javascript
【发布时间】:2016-08-14 02:03:45
【问题描述】:
我想在客户端使用 HTML5 将“图像对象”转换为“文件对象”,以将文件上传到 azure blob 存储。
由于我使用的是 AngularJs,我的计划是
我找到了很多使用 FileReader 将 File 对象转换为图像的示例,但我找不到相反的示例。
听说用客户端javascript无法将文件写入本地文件系统,但我不需要存储文件,我只需要文件对象引用来上传文件。
有没有办法解决这个问题?
【问题讨论】:
标签:
javascript
html
image
【解决方案1】:
您可以使用 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)
;
对于您的情况,只需将 '/images/logo.png' 替换为 imageObject.src
【解决方案2】:
有一种方法可以通过 File System API 将文件保存到本地文件系统,但只有 Chrome 和 Opera 支持。如果你想将一个图像文件从 File/Blob 渲染到一个 IMG 标签,你可以这样做
img.src = URL.createObjectURL(myFileOrBlob);
这会将文件/Blob 转换为 URL,该 URL 仅在您的浏览器内部可用,看起来像这样
blob:http%3A//localhost/2ee59cd6-9220-429c-add9-05983645639e
使用完图片后,最好通过这样做来释放内存
URL.revokeObjectURL(blobURL);
希望我对您的理解正确,对您有所帮助。