儲存檔案到本地

weixin_34214500發表於2018-01-17
export default (data, name='sprite', suffix='xxx') => {
  const contentType = {
    // 基本型別
    'txt': 'text/plain',
    'png': 'image/png',
    'jpeg': 'image/jpeg',
    'jpg': 'image/jpeg',
    // 自定義型別
    'xxx': 'text/plain',
  };
  if (contentType[suffix]) {
    const fileName = name + '.' + suffix;
    const file = new Blob([JSON.stringify(data)], { type: contentType[suffix] });
    if (window.navigator.msSaveOrOpenBlob) { // IE10+
      window.navigator.msSaveOrOpenBlob(file, fileName);
    } else {
      // Others
      const a = document.createElement('a');
      const url = URL.createObjectURL(file);
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      // 下一個事件迴圈,刪除掉 a 元素
      setTimeout(function () {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }, 0);
    }
    console.log('File has been saved:', fileName);
  } else {
    console.log('File not saved. Suffix not exist:', suffix);
  }
};

相關文章