use-strict / 7z-wasm

7-Zip for JavaScript environments, compiled to WASM
Other
109 stars 7 forks source link

read from blob #21

Closed vinnitu closed 1 year ago

vinnitu commented 1 year ago

Hello. Glory to Ukraine!

I have

<input type='file' onchange='on7z' accept='.7z'>
import SevenZip from "7z-wasm";

cosnt on7z = async (e) => {
  const sevenZip = await SevenZip();
  // how to read e.target.file[0] ?
}
use-strict commented 1 year ago

You need to read the file as an ArrayBuffer, then make a Uint8Array out of it. Then you can just follow the example in the README.

If there isn't a real bug or problem concerning the project itself, please use Stackoverflow, ChatGPT or ye olde Google instead. Thanks.

vinnitu commented 1 year ago

Update...

<input type="file" @change="on7z" accept=".7z">
const readFile = (file, method = 'readAsText') => new Promise((resolve, reject) => {
  var fileReader = new FileReader();
  fileReader.onload = () => resolve(fileReader.result);
  fileReader.onerror = reject;
  fileReader[method](file);
});

const on7z = async (e) => {
  const data = await readFile(e.target.files[0], 'readAsArrayBuffer');
  const archiveData = new Uint8Array(data);

  const stdout = [];
  const sevenZip = await SevenZip({
    locateFile: s => s,
    stdout: s => stdout.push(s)
  });

  const archiveName = "archive.7z";
  const stream = sevenZip.FS.open(archiveName, 'w+');
  sevenZip.FS.write(stream, archiveData, 0, archiveData.length);
  sevenZip.FS.close(stream);

  await sevenZip.callMain(["e", archiveName, '-so']);
  const decoder = new TextDecoder('utf-8');
  const result = decoder.decode(new Uint8Array(stdout))
}

It works. Thanks.