amrrragab
amrrragab

Reputation: 3

copy selected file from an input on electron app form

I have this form

<form>
  <input type="file" name="idp" id="idp" onchange="uploadFiles();"/>
</form>

When the user chooses a picture I need to copy it to a specified folder and store its full name into a variable to save it into the database.

I've tried this code:

const electron = require('electron');
const { dialog } = electron;    // electron.remote; (if in renderer process)
const fs = require('fs');       // module that interacts with the file system
const path = require("path"); 
function uploadFiles(){
    // opens a window to choose file
    dialog.showOpenDialog({properties: ['openFile']}).then(result => {

        // checks if window was closed
        if (result.canceled) {
            console.log("No file selected!")
        } else {

            // get first element in array which is path to file selected
            const filePath = result.filePaths[0];

            // get file name
            const fileName = path.basename(filePath);

            // path to app data + fileName = "C:\Users\John\AppData\Roaming\app_name\picture.png"
            imgFolderPath = path.join(app.getPath('userData'), fileName);

            // copy file from original location to app data folder
            fs.copyFile(filePath, imgFolderPath, (err) => {
                if (err) throw err;
                console.log(fileName + ' uploaded.');
            });
        }
    });
};

and it gives me this error message on the console:

Uncaught TypeError: Cannot read property 'showOpenDialog' of undefined
    at uploadFiles 
    at HTMLInputElement.onchange

Upvotes: 0

Views: 724

Answers (1)

spring
spring

Reputation: 18487

const { dialog } = electron;    // electron.remote; (if in renderer process)

It appears that you are calling this from a renderer process. Therefore you need to use electron.remote in order to access the dialog module (as the code example you are using above indicates).

It's worth taking the time to read up on themain and renderer processes in Electron – they are fundamental concepts that you will encounter over and over and they are especially important in IPC messaging

Upvotes: 1

Related Questions