Neutralino pick file然后readFile不工作



我选择一个文件,然后从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);});  
});

在我的例子中,当我在桌面上选择一个文件时,返回的路径__data[0]

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

但是当我试图读取文件时,它无声地失败了。如何加载一个不是相对路径的文件?我没有问题加载文件与相对路径。

readFilefor ">[reading] a文本文件"。你需要的是readBinaryFile

在JavaScript中从二进制文件创建图像是很常见的,并且有很好的文档,这里有一些资源:

  • MDN -使用对象url显示图像
  • MDN - Blob
  • 随机要点我发现

使用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;

最新更新