DEV Community

Cover image for How To Read Uploaded File Content In JavaScript
IderaDevTools
IderaDevTools

Posted on

How To Read Uploaded File Content In JavaScript

Web developers have many reasons to read uploaded file content in JavaScript. Instead of uploading them straight to the client, they can write and manipulate the file data from a local directory. Compatibility issues on the JavaScript file uploader are easier to resolve before any data gets transported across the server. To illustrate this, let’s observe the File Reader object, which treats the content as a data URL.

function readImage(file) {

 // Check if the file is an image.

 if (file.type && !file.type.startsWith('image/')) {

   console.log('File is not an image.', file.type, file);

   return;

 }

 const reader = new FileReader();

 reader.addEventListener('load', (event) => {

   img.src = event.target.result;

 });

 reader.readAsDataURL(file);

}
Enter fullscreen mode Exit fullscreen mode

Whenever a user selects a file, they act on an HTML input controlled by a change event. The file is then converted to a full-sized img element. Reading a file is an important operation because some programs have to perform algorithm training, compile report findings, or store large sets of data. The JavaScript file uploader enables asynchronous file reading through the browser, either via the promise API or the “select file” attribute.

As such, the final output of a file read is always conducted on the server side since it won’t be visible in the browser unless you print out each line of the console.

How Do You Interact With Uploaded Text Files On A JS Framework?

Oftentimes, the File Reader API permits a web application to save a file reference even when the user is offline. In this section, we will focus on the event handler FileReader.readAsArrayBuffer() while it returns an ArrayBuffer version of the local file. Conversely, the FileReader.readAsText() method returns the content as a text string to improve its legibility.

var myFile = document.getElementById("myFile");

var fileOutput = document.getElementById("fileOutput");

myFile.addEventListener('change',function(){

   var fileReader=new FileReader();

   fileReader.onload=function(){

      fileOutput.textContent=fileReader.result;

   }

   fileReader.readAsText(this.files[0]);

})

}
Enter fullscreen mode Exit fullscreen mode

Use the select file HTML to initialize an input form that records the file name. Next, get a reference of your input file by passing in its id. Now, add an event listener to detect the chosen file. In the line after, we can call the readAsText() method on the first file in the list. Inside the change event, define a file reader object. For the load function, set the output equal to the result of your file. And finally, confirm that the file reader is not selecting multiple files.

Furthermore, you can read a text file by importing the React component and define an app class that extends it to retrieve all the available properties. Create a constructor instance with the props argument which is called during the mounting process.

Is It Possible To Interpret A React File Upload?

To fetch the file data, use the Async library to launch the File Reader API from React. Assign a new FileReader() object to a variable, then use an onload function to grab the file information from an array of selected files or e.target.files[0] in this case.

It should then be passed into a readAsText() method. Check that it is rendered properly by printing the resulting text in your console. Notice how each file relies on a FormData object to load its raw data in the app.

The following code summarizes the steps involved in a React.js file upload:

Event.target.files 

import React, { Component } from 'react'; 

class App extends Component { 

   constructor(props) { 

   super(props); 

   } 

   showFile = async (e) => { 

      e.preventDefault() 

      const reader = new FileReader() 

      reader.onload = async (e) => { 

         const text = (e.target.result) 

         console.log(text) 

         alert(text) 

      }; 

      reader.readAsText(e.target.files[0]) 

   } 

render = () => { 

   return (<div> 

      <input type="file" onChange={(e) => this.showFile(e)} /> 

   </div> ) 

   } 

} 
Enter fullscreen mode Exit fullscreen mode
export default App;
Enter fullscreen mode Exit fullscreen mode

However, if you’re aiming for a PHP solution, you should consult this article on installing the PHP file uploader. It provides a thorough introduction to the PHP SDK, a CMS/API engineered to transform files and serve them on a private cloud, where they can be tagged and securely modified. One neat feature is uploading files in chunks of any size, thus stabilizing the server without impacting the network latency.

In similar terms, if you’re tackling a CSV Python file upload, this article from Filestack will guide you on what to do with the file path as well as how to display the imported data in Python. All you really need is the file name and extension followed by the pandas module for calling the read_csv (location) method. That said, sorting the data by rows or columns is entirely optional.

How Does Filestack’s Document Viewer Compare To A JavaScript File Uploader?

The Document Viewer delivers a file preview in the user’s browser using the Filestack processing engine and the custom solution outlined on Mozilla’s PDF.js. So far, it supports file types from PDF to DOCx and jpg to even plain text, leveraging a CDN to carry out file uploads by accessing a cached copy of their URLs. The preview handle of the file URL allows PDF content to be embedded in a webpage.

The JavaScript client will generate an iframe element inheriting the document preview in read-only mode. Additionally, developers intending to preview files in the browser can do so in slide view. The slider API responds to an array of handles, containing parameters to change the theme or conversion engine.

Overall, Filestack goes above and beyond by ensuring reliable uploads, transformations, and deliveries, serving as an API and CDN hybrid. For delivery of larger files, you’ll get to experience a fully-optimized product that comes with instant viewing on almost any device.

Set up an account now to begin the trial version.

Top comments (0)