【问题标题】:Get input file path using NeutralinoJS使用 NeutralinoJS 获取输入文件路径
【发布时间】:2021-05-31 14:16:40
【问题描述】:

如何使用 NeutralinoJS 获取输入文件路径?

我的代码:

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

【问题讨论】:

  • 出于安全原因,浏览器不允许您在客户端访问或读取文件路径。

标签: javascript html neutralinojs


【解决方案1】:

我认为浏览器不允许您获取文件路径。

您可以改用文件选择器 API 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}`)
}

【讨论】:

    【解决方案2】:

    为什么需要路径?如果您需要上传文件中的内容,您可以通过 javascript filereader API 获取并使用这些内容。 如果您需要该文件以供以后使用,您可以通过 js filereader 读取该文件,然后使用filesystem.writeFile(WriteFileOptions) 创建一个新文件并将其保存到您的首选位置(可能是应用程序内部临时路径)。确保目标路径存在。为此,您可以使用filesystem.createDirectory(CreateDirectoryOptions)

    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
        });
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用Neutralino.os API 来显示打开/保存文件对话框。

      这是打开文件的示例。

      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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-27
        • 2013-12-20
        • 2023-04-01
        • 2020-01-07
        • 2017-03-16
        • 2015-10-26
        • 2016-02-19
        • 1970-01-01
        相关资源
        最近更新 更多