简体   繁体   中英

Save an object using blob api. How?

How can trigger a local to local download of an object as a json file using the Blob API ?

const obj = {

  prop1: 'val1',
  prop2: 'val2',
  prop3: 'val3',
  prop4: 'val4',

}

const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'});

...triggers a local to local download as myObject.json

Declaring this does nothing?

Do this to get the url. Then navigate to it to download the file.

let blobUrl = URL.createObjectURL(new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'}))

Or if you want to download it straight away (edit: by using a library):

saveAs(new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'}), "myBlob"); // "myBlob" is the name of the file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM