Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

javascript - Error when attempting to create a blob from a JSON.stringified object

I have an object that is stringified successfully, but then there's an error when a blob is attempted to be created from it: "Uncaught TypeError: Failed to construct 'Blob': The provided value cannot be converted to a sequence." A file with the proper name is then successfully downloaded, but it has no contents. Might someone know what I'm doing wrong when creating the Blob? Thanks!

This is the code I'm using for exporting the file:

const data = JSON.stringify(arrayObject);
const blob1 = new Blob(data, { type: "text/plain;charset=utf-8" });
const name = this.currentUser.username + ".json";

//Check the Browser.
const isIE = false || !!document.documentMode;
if (isIE) { window.navigator.msSaveBlob(blob1, name); }
else {
    const url = window.URL || window.webkitURL;
    const link = url.createObjectURL(blob1);
    var a = $("<a />");
    a.attr("download", name);
    a.attr("href", link);
    $("body").append(a);
    a[0].click();
    $("body").remove(a);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

https://javascript.info/blob describes the constructor syntax as new Blob(blobParts, options), where blobParts is an array of Blob/BufferSource/String values. The issue is fixed when the first line is changed to the following:

const data = [JSON.stringify(arrayObject)];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...