将图像对象转换为文件对象,javascript

Converting image object to File object, javascript

本文关键字:对象 javascript 文件 转换 图像      更新时间:2023-09-26

我想在客户端使用 HTML5 将"图像对象"转换为"文件对象",以将文件上传到 Azure blob 存储。

由于我使用的是AngularJs,我的计划是

  • 将图像转换为文件
  • 使用 Angular-Azure-Blob-upload 将文件上传到 Blob 存储

我找到了很多使用 FileReader 将 File 对象转换为图像的示例,但我找不到相反的示例。

听说不可能用客户端javascript将文件写入本地文件系统,但我不需要存储文件,我只需要文件对象引用来上传文件。

有没有办法解决这个问题?

您可以使用 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

有一种方法可以通过文件系统API将文件保存到本地文件系统,但只有Chrome和Opera支持它。如果要将图像文件从文件/斑点渲染到 IMG 标签,可以

img.src = URL.createObjectURL(myFileOrBlob);

这会将文件/Blob 转换为 URL,该 URL 仅在浏览器中可用,如下所示

blob:http%3A//localhost/2ee59cd6-9220-429c-add9-05983645639e

使用完图像后,最好通过执行

URL.revokeObjectURL(blobURL);

希望我正确理解你,这对你有帮助。