如何在JavaScript中将Blob转换为File

ski*_*kip 81 javascript blob file-upload node.js

我需要将图像上传到NodeJS服务器到某个目录.我正在使用connect-busboy节点模块.

dataURL使用以下代码将我转换为blob的图像:

dataURLToBlob: function(dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) {
        var parts = dataURL.split(',');
        var contentType = parts[0].split(':')[1];
        var raw = decodeURIComponent(parts[1]);
        return new Blob([raw], {type: contentType});
    }
    var parts = dataURL.split(BASE64_MARKER);
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;
    var uInt8Array = new Uint8Array(rawLength);
    for (var i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {type: contentType});
}
Run Code Online (Sandbox Code Playgroud)

我需要一种方法将blob转换为文件以上传图像.

有人可以帮我吗?

小智 147

您可以使用File构造函数:

var file = new File([myBlob], "name");
Run Code Online (Sandbox Code Playgroud)

根据w3规范,这将将blob包含的字节附加到新File对象的字节,并创建具有指定名称的文件 http://www.w3.org/TR/FileAPI/#dfn-file

  • Edge目前(2017-10-04)是一个阻止使用此构造函数的错误.https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9551546/ (7认同)
  • 文件构造函数在PhantomJS中不起作用:`TypeError:FileConstructor不是构造函数(评估'new File([''],'file.pdf',{'size':1000,'type':'application/pdf' })')` (4认同)
  • 请确保添加文件类型,否则它将无法正常工作。新文件([myBlob],“名称”,{类型:“ image / jpeg”,}); (3认同)
  • 这就是我要找的,一个区别是第一个参数实际上是一个数组所以我用它作为:var file = new File([myBlob],"name"); (2认同)
  • 是的。我也在寻找这个解决方案。Stamplay 服务器无法从 blob 对象获取文件名。所以我需要将其转换回文件。但 Safari 不支持文件 API...现在回到 0 :( (2认同)

CBa*_*arr 122

此函数将a转换Blob为a File,它对我来说非常有用.

香草JavaScript

function blobToFile(theBlob, fileName){
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}
Run Code Online (Sandbox Code Playgroud)

TypeScript(正确的打字)

public blobToFile = (theBlob: Blob, fileName:string): File => {
    var b: any = theBlob;
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    b.lastModifiedDate = new Date();
    b.name = fileName;

    //Cast to a File() type
    return <File>theBlob;
}
Run Code Online (Sandbox Code Playgroud)

用法

var myBlob = new Blob();

//do stuff here to give the blob some data...

var myFile = blobToFile(myBlob, "my-image.png");
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个好的解决方案,生产的对象仍然是一个blob. (7认同)
  • 这不应该是公认的答案,/sf/answers/3724403791/ 或 /sf/answers/2216455181/ 应该是。 (5认同)
  • 只需添加`b .__ proto__ = File.prototype`,你的解决方案就成了一个梦想,甚至可以把`b instanceOf File`欺骗为'true` (4认同)
  • 我认为演员阵容应该首先发生,所以你不需要在TypeScript中使用`any`.见[this](http://www.typescriptlang.org/play/#src=function%20blobToFile(blob%3A%20Blob%2C%20fileName%3A%20string)%3A%20File%20%7B%0A%09 %2F%2FA%20Blob%图20是%20almost%20A%20File%20-%20IT的%20just%20missing%第二十条%20two%20properties%20below%0A%20%20%20%20var%20F%20%3D%20% 3CFile%3EtheBlob%3B%0A%20%20%20%20f.lastModifiedDate%20%3D%20new%20Date()%3B%0A%20%20%20%20f.name%20%3D%20fileName%3B% 0A%0A%20%20%20%20return%20f%3B%0A%7D)例子. (3认同)
  • 这不适用于所有目的.将此"文件"添加到ajax调用将不会正确设置文件名. (2认同)

Ale*_*urt 22

为了让我工作,我必须明确提供类型,尽管它包含在 blob 中:

const file = new File([blob], 'untitled', { type: blob.type })
Run Code Online (Sandbox Code Playgroud)


Hos*_*hef 21

打字稿

public blobToFile = (theBlob: Blob, fileName:string): File => {       
    return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}
Run Code Online (Sandbox Code Playgroud)

Javascript

function blobToFile(theBlob, fileName){       
    return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
}
Run Code Online (Sandbox Code Playgroud)

输出

截屏

File {name: "fileName", lastModified: 1597081051454, lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time), webkitRelativePath: "", size: 601887, …}
lastModified: 1597081051454
lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time) {}
name: "fileName"
size: 601887
type: "image/png"
webkitRelativePath: ""
__proto__: File
Run Code Online (Sandbox Code Playgroud)


mil*_*ili 15

约书亚·尼克松Joshua P Nixon)的回答是正确的,但我也必须设定最后修改日期。所以这是代码。

var file = new File([blob], "file_name", {lastModified: 1534584790000});
Run Code Online (Sandbox Code Playgroud)

1534584790000是Unix时间戳“ GMT:星期六,2018年8月18日上午九时33分10秒

  • 没有像接受的答案那样破坏`instanceof`的要点 (4认同)
  • 旁注,如果有人这样做并且不想硬编码它的最后修改时间是 2018 年 8 月,您可以随时输入“lastModified: Date.now()”,这将返回当前时间(以毫秒为单位)!(就像给出的示例是 2018 年 8 月 18 日 9:33:10(以毫秒为单位)) (2认同)

DAV*_*D _ 9

我的现代变体:

function blob2file(blobData) {
  const fd = new FormData();
  fd.set('a', blobData);
  return fd.get('a');
}
Run Code Online (Sandbox Code Playgroud)

  • 要将文件名添加到生成的文件中,请使用:`fd.set('a', blobData, 'filename')` (3认同)

Ron*_*ald 5

var blob = new Blob(["Hello, world!"], { type: "text/plain;charset=utf-8" });

var file = new File([blob], "name.txt");
Run Code Online (Sandbox Code Playgroud)

现在您可以上传为 .txt 文件