簡體   English   中英

如何在 JavaScript 中將 Blob 轉換為文件

[英]How to convert Blob to File in JavaScript

我需要將圖像上傳到 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});
}

我需要一種將 blob 轉換為文件以上傳圖像的方法。

有人可以幫我嗎?

您可以使用 File 構造函數:

var file = new File([myBlob], "name");

根據 w3 規范,這會將 blob 包含的字節附加到新 File 對象的字節中,並創建具有指定名稱http://www.w3.org/TR/FileAPI/#dfn-file的文件

此函數將Blob轉換為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;
}

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;
}

用法

var myBlob = new Blob();

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

var myFile = blobToFile(myBlob, "my-image.png");

Joshua P Nixon的回答是正確的,但我也必須設置最后修改日期。 所以這里是代碼。

var file = new File([blob], "file_name", {lastModified: 1534584790000});

1534584790000是“格林威治標准時間:2018 年 8 月 18 日星期六上午9:33:10”的 unix 時間戳

打字稿

public blobToFile = (theBlob: Blob, fileName:string): File => {       
    return new File(
        [theBlob as any], // cast as any
        fileName, 
        {
            lastModified: new Date().getTime(),
            type: theBlob.type 
        }
    )
}

Javascript

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

輸出

截屏

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

為了工作,我必須明確提供類型,盡管它包含在 blob 中:

const file = new File([blob], 'untitled', { type: blob.type })

我的現代變體:

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

我需要將圖像上傳到NodeJS服務器到某個目錄。 我為此使用connect-busboy節點模塊。

我有使用以下代碼轉換為blob的圖像的dataURL

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});
}

我需要一種將Blob轉換為文件以上傳圖像的方法。

有人可以幫我嗎?

這個問題困擾了我好幾個小時。 我正在使用 Nextjs 並嘗試將畫布轉換為圖像文件

我使用了其他人的解決方案,但創建的文件是的。

因此,如果這是您的問題,您應該在文件對象中提及size屬性。

new File([Blob], `my_image${new Date()}.jpeg`, {
  type: "image/jpeg",
  lastModified: new Date(),
  size: 2,
});

只需添加不重要的值即可。

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

var file = new File([blob], "name.txt");

現在你可以上傳 as.txt 文件了

我使用FileSaver.js將 blob 保存為文件。

這是回購: https ://github.com/eligrey/FileSaver.js/

用法:

import { saveAs } from 'file-saver';

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

saveAs("https://httpbin.org/image", "image.jpg");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM