A
A
askold20132018-03-15 19:57:42
JavaScript
askold2013, 2018-03-15 19:57:42

How to read a binary file in the browser, just like using fs?

Hello!
The problem was revealed in the next moment - I need to sign the file in the browser, and verify the signature on the server, i.e. in the browser and on the server I need to read the file in the same way. On the server, everything is simple:
const fileDocument = fs.readFileSync(pathToFile)
And we get such a buffer

<Buffer 25 50 44 46 2d 31 2e 33 0d 0a 25 e2 e3 cf d3 0d 0a 34 20 30 20 6f 62 6a 0d 0a 3c 3c 0d 0a 2f 54 79 70 65 20 2f 50 61 67 65 0d 0a 2f 50 61 72 65 6e 74 ... >

The problem is how can I do the same in the browser. What I tried:
Api.documentsApi
    .getFileContent(context.state.document.versions[0].file,
         { ...store.getters['headerToken'], responseType: 'blob' })
          .then(blob => {
            console.log(blob)
            // read file content
            let fileContent = ''
            const fr = new FileReader()
            fr.readAsArrayBuffer(blob)
            fr.onload = (file) => { fileContent = file.target.result }

1. I request from the server the file blob I need
2. Using FileReader I read it as a buffer (like the same as in fs?)
3. and ... I get an empty string in the console (fileContent after all this is an empty string)
How do I get the same result as in fs on the server? Do not create the same temporary file in the browser

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2018-03-15
@Gentlee

onload is called asynchronously.

const reader = new FileReader();
reader.onload = event => {
    let fileContent = event.target.result;
    console.log(fileContent);
}
reader.readAsArrayBuffer(blob);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question