javascriptneutralinojs

Neutralino pick file then readFile not working


I select a file then read the file from the path returned by Neutralino.

 Neutralino.os.showOpenDialog('Select Image', {
        filters: [
            {name: 'Images', extensions: ['jpg', 'png']}
        ]
    }).then((__data) => {
        Neutralino.filesystem.readFile(__data[0]).then((__string) => {
            console.log('LOADED', __string);               
        }, (__error) => {console.log('ERR', __error)}).catch(__error => {console.log('Error', __error);});  
    });

In my case, when I select a file on the desktop for instance, the returned path __data[0] is

 C:/Users/Eric/Desktop/1595887262047.jpg

But then when I try to read the file, it silently fails. How do I load a file that is not a relative path?? I have no issue loading files with a relative path.


Solution

  • readFile is for "[reading] a text file". What you need is readBinaryFile.

    Creating an image from binary in JavaScript is commonly done and well documented, here are some resources:

    One possible implementation using SolidJS:

    import logo from "./logo.svg";
    import styles from "./App.module.css";
    
    import { createSignal } from "solid-js";
    
    function App() {
      const [img, setImg] = createSignal(logo);
    
      const handleFileChosen = (imgPath) => {
        Neutralino.filesystem
          .readBinaryFile(imgPath) // Read the image
          .then((imgData) => {
            // Get image extension e.g. png
            const ext = imgPath.split(".").pop();
    
            // Create a Blob using the returned ArrayBuffer data,
            // You need to specify what type of file it is
            const blob = new Blob([imgData], { type: `image/${ext}` });
    
            // Turn Blob into something we can use on <img> element
            const objectUrl = URL.createObjectURL(blob);
            setImg(objectUrl);
          })
          .catch((err) => {
            console.warn(err);
          });
      };
    
      const handleFileDialog = () => {
        // Just in case it hasn't loaded yet
        Neutralino?.os
          .showOpenDialog("Select Image", {
            filters: [{ name: "Images", extensions: ["jpg", "png"] }],
          })
          .then((imgPaths) => {
            // Call with returned image path
            handleFileChosen(imgPaths[0]);
          })
          .catch((err) => {
            console.warn(err);
          });
      };
    
      return (
        <div class={styles.App}>
          <header class={styles.header}>
            <img src={img()} class={styles.logo} alt="logo" />
            <!-- ... -->
            <button type="button" onClick={handleFileDialog}>
              Choose Image
            </button>
          </header>
        </div>
      );
    }
    
    export default App;