Get input file path using NeutralinoJS

1k views Asked by At

How do I get input file path using NeutralinoJS?

My Code:

<input type="file" id="inputFile">
const inputFilePath = document.getElementById('inputFile').files[0].path
console.log(inputFilePath)
3

There are 3 answers

0
AlekseyHoffman On

I don't think browsers allow you to get file paths.

You could use the file picker API instead os.showDialogOpen(DialogOpenOptions): https://neutralino.js.org/docs/api/os#osshowdialogopendialogopenoptions

<button onclick="onFileUpload()">
async onFileUpload () {
  let response = await Neutralino.os.showDialogOpen({
    title: 'Select a file'
  })
  console.log(`You've selected: ${response.selectedEntry}`)
}
0
rince On

Why do you need the path? If you need the content from the upload file you can get it via javascript filereader API and use the contents. If you need the file for later use you can read the file via js filereader and then create and save a new file with filesystem.writeFile(WriteFileOptions) to your prefered location (maybe app internal temp path). Be sure the destination path exists. For that you can use filesystem.createDirectory(CreateDirectoryOptions).

Example with jQuery:

jQuery(document).on('change','#myUpload',function(){ //Click on file input
  if(jQuery(this).val().length > 0){ //Check if a file was chosen
    let input_file = this.files[0];
    let file_name = input_file.name;
    let fr = new FileReader();
    fr.onload = function(e) {
        fileCont = e.target.result;
        //Do something with file content
        saveMyFile(file_name, fileCont); //execute async function to save file
    };
    fr.readAsText(input_file);
  }
});

async function saveMyFile(myFileName, myFileContent){
    await Neutralino.filesystem.createDirectory({ path: './myDestPath' }).then(data => { console.log("Path created."); },() => { console.log("Path already exists."); }); //create path if it does not exist
    //write the file:
    await Neutralino.filesystem.writeFile({
        fileName: './myDestPath/' + myFileName,
        data: myFileContent
    });
}
0
Aditya On

You can use the Neutralino.os API for showing the Open/Save File Dialogs.

This is A Example For Opening A File.

HTML:

<button type="button" id="inputFile">Open File</button>

JavaScript:

document.getElementById("inputFile").addEventListener("click", openFile);

async function openFile() {
  let entries = await Neutralino.os.showOpenDialog('Save your diagram', {
    filters: [
      {name: 'Images', extensions: ['jpg', 'png']},
      {name: 'All files', extensions: ['*']}
    ]
  });
  console.log('You have selected:', entries);
}