LoginSignup
0
2

More than 5 years have passed since last update.

お手軽にブラウザ上のjsコードで使うデータのバックアップと復帰を行いたい

Posted at

ダウンロード

クライアントの内部データを手軽にバックアップしたい時に使っているコードです。


async function download(data: any, filename: string) {
  let blob = new Blob([data], { 'type': 'octet/stream' });
  let a = document.createElement('a');
  a.href = window.URL.createObjectURL(blob);
  a.download = `${filename}`;
  a.click();
}

アップロード

復帰させたい場合


function upload(): Promise<string> {
  let input = document.createElement('input');
  input.type = 'file';
  return new Promise<string>(resolve => {
    input.addEventListener('change', async (e) => {
      let files = input.files;
      if (files === null) { return; }
      if (files.length <= 0) { return; }
      const file = files.item(0);
      let text = await readAsText(file);
      resolve(text);
    });
    input.click();
  });
}

const readAsText = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => resolve(reader.result as string);
    reader.onerror = e => reject(`Error reading ${file.name}: ${reader.result}`);
    reader.readAsText(file);
  });
};


サンプルコード

こちらに動くサンプルを置いています

サンプルを含めたコードはこちらです。


async function download(data: any, filename: string) {
  let blob = new Blob([data], { 'type': 'octet/stream' });
  let a = document.createElement('a');
  a.href = window.URL.createObjectURL(blob);
  a.download = `${filename}`;
  a.click();
}

 const readAsText = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => resolve(reader.result as string);
    reader.onerror = e => reject(`Error reading ${file.name}: ${reader.result}`);
    reader.readAsText(file);
  });
};

function upload(): Promise<string> {
  let input = document.createElement('input');
  input.type = 'file';
  return new Promise<string>(resolve => {
    input.addEventListener('change', async (e) => {
      let files = input.files;
      if (files === null) { return; }
      if (files.length <= 0) { return; }
      const file = files.item(0);
      let text = await readAsText(file);
      resolve(text);
    });
    input.click();
  });
}


let text = '';

let b = document.createElement('button');
b.innerText = "upload";
b.onclick = async () => {
  text = await upload();
  let pre = document.createElement('pre');
  pre.innerText = text;
  document.body.appendChild(pre);
}

let b2 = document.createElement('button');
b2.innerText = "download";
b2.onclick = async () => {
  await download(text, 'text.txt')
  alert('download')
}

document.body.appendChild(b);
document.body.appendChild(b2);

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2