須要將文件導出保存到本地前端
參考文章以下 :git
前端利用Blob對象建立指定文件並下載github
MDN的blob概念npm
Blob對象表示一個不可變、原始數據的類文件對象。Blob 表示的不必定是JavaScript原生格式的數據。File接口基於Blob,繼承了blob的功能並將其擴展使其支持用戶系統上的文件。json
var aBlob = new Blob( array, options );
複製代碼
var debug = {hello: "world"};
var blob = new Blob([JSON.stringify(debug, null, 2)], {type : 'application/json'});
複製代碼
安裝fileSaver(github地址)segmentfault
npm install file-saver --save
複製代碼
// 引入模塊
import FileSaver from 'file-saver';
export default class App extends Component {
// 點擊下載
downFile = () => {
this.download();
}
// 下載文件
download() {
// 要輸出的文件內容
let particleData = store.getEmitterJson;
// 將指定數據轉換爲 JSON 字符串
let content = JSON.stringify(particleData, null, 2);
// 數組內容的MIME類型爲json
let type = "data:application/json;charset=utf-8";
// 實例化Blob對象,並傳入參數
let blob =new Blob([content], {type: type});
let isFileSaverSupported = false;
try {
isFileSaverSupported = !!new Blob();
} catch (e) {
console.log(e);
}
if (isFileSaverSupported) {
FileSaver.saveAs(blob,"particleData.json");
}else{
FileSaver.open(encodeURI(type + "," + content));
}
}
}
複製代碼