Open In App

File Upload in ElectronJS

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime. Any native desktop application should integrate itself with the System OS environment. The application should have the ability to interact with core OS functionalities such as the File System, System Tray, etc. Electron provides us with built-in dialog module to display the native System dialogs for interacting with files. This tutorial will use the instance method of the dialog module to demonstrate File Upload functionality in Electron. We assume you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system. Dialog Module: The dialog Module is part of the Main Process. To import and use the dialog Module in the Renderer Process, we will be using Electron remote module.

Example: We will start by building the Electron Application for File Upload functionality by following the given steps.

npm init
npm install electron --save
npm install axios --save
{
  "name": "electron-fileupload",
  "version": "1.0.0",
  "description": "File Upload in Electron",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "keywords": [
    "electron"
  ],
  "author": "Radhesh Khanna",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.19.2",
    "electron": "^8.2.5"
  }
}




const { app, BrowserWindow } = require('electron')
 
function createWindow () {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })
 
  // Load the index.html of the app.
  win.loadFile('src/index.html')
 
  // Open the DevTools.
  win.webContents.openDevTools()
}
 
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
// This method is equivalent to 'app.on('ready', function())'
app.whenReady().then(createWindow)
 
// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // To stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
 
app.on('activate', () => {
  // On macOS it's common to re-create a window in the 
  // app when the dock icon is clicked and there are no
  // other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})
 
// In this file, you can include the rest of your
// app's specific main process code. You can also
// put them in separate files and require them here.




<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
                           /security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy"
          content="script-src 'self' 'unsafe-inline';" />
  </head>
  <body>
    <h1>Hello World!</h1> We are using node
    <script>
         document.write(process.versions.node)
    </script>, Chrome
    <script>
         document.write(process.versions.chrome)
    </script>, and Electron
    <script>
         document.write(process.versions.electron)
    </script>.
 
    <h3>File Upload in Electron</h3>
    <button id="upload">Upload File</button>
     
    <!-- Adding Individual Renderer Process JS File -->
    <script src="index.js"></script>
  </body>
</html>

npm start




const fs = require('fs');
const axios = require('axios');
 
if (global.filepath && !file.canceled) {
         var formData = new FormData();
         formData.append('file', fs.createReadStream(global.filepath));
         axios.post('[Custom URL]', formData, {
         headers: {
            'Content-Type': 'multipart/form-data'
           }
        });
      }
 
// ...




const fs = require('fs');
const fs = require('fs');
 
if (global.filepath && !file.canceled) {
  fs.readFile(global.filepath, {encoding: 'utf-8'}, function(err,data) {
     if (!err) {
          console.log('received data: ' + data);
     } else {
          console.log(err);
      }
   });
 }
 
//...


Article Tags :