Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does 'fetch' method present the same functionality as 'FileReader'?

Tags:

I managed to read the text file byte by byte and to change the charset from windows-1251 to Unicode for a file loaded from the end user's computer via an input element and FileReader. Now I want to do the same thing for a file from my server, via fetch. Is it possible to do that? (The fetch would be in a page served via HTTP and the URL would be relative, e.g. fetch("raw/graph_tab.txt") — I'm not trying to read a file directly from the end user's machine as I was with an input field and FileReader).

Chunks of working code ('windows-1251.js' library is created by Mathias Bynens):

<input type="file" id="file"/>
<script type="text/javascript">
        document.getElementById("file").addEventListener("change", readFile, false);

        function readFile (evt) {
            var files = evt.target.files;
            var file = files[0];           
            var reader = new FileReader();
            reader.onload = function(event) {
                console.log(windows1251.decode(event.target.result));            
            }};
like image 295
Andrey Avatar asked Jan 06 '19 13:01

Andrey


People also ask

What does the fetch () method do?

fetch() The global fetch() method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the Response object representing the response to your request.

What is difference between XHR and fetch?

XHR is an old way make requests to the server. Fetch API is a modern way to make requests to the server. Chaining is difficult in XHR, but in fetch you can easily chain the promises. In XHR we need to check the status property for the errors, but in fetch the catch method is there to handle errors.

What does FileReader do in JavaScript?

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

What are the disadvantages of fetch API?

more complicated API, request and response concepts are mixed together. lacks streaming, whole response is going to buffer in memory, not available for binary data.


1 Answers

If you mean you want to have the encoding parameter of the FileReader.readAsText(Blob, encoding) method, then you'd set a charset parameter in the Content-Type header of your response.

If this is not doable for whatever reason, then you'd have to consume your Response object to a Blob using its Body.blob() method, and then pass the resulting Blob to a FileReader.

Otherwise, no, even though the Response object has similar methods than the ones of a FileReader, the text() method doesn't provide an encoding option...

like image 131
Kaiido Avatar answered Nov 29 '22 05:11

Kaiido