[英]Get created file's path from SaveFileDialog in electron
我試圖在使用 SaveFileDialog 后存儲我創建的文件的路徑,這是我的代碼:
let path;
dialog.showSaveDialog((fileName) => {
if (fileName === undefined){
console.log("You didn't save the file");
return;
}
fs.writeFile(fileName, text, (err) => {
if(err){
alert("An error ocurred creating the file "+ err.message)
}
alert("The file has been succesfully saved");
});
});
我想要發生的是,在用戶創建文件后,他將在變量路徑中輸入文件的路徑,這甚至可能嗎?
您可以使用dialog.showSaveDialog
的同步版本。 使用同步版本不需要你聲明路徑變量而不初始化它
let path = dialog.showSaveDialog( {
title: "Save file",
filters: [ { name:"png pictures", ext: [ "png" ] } ], // what kind of files do you want to see when this box is opend
defaultPath: app.getPath("document") // the default path to save file
});
if ( ! path ) {
// path is undefined
return;
}
fs.writeFile( path , text , ( err , buf ) => {
if ( err )
return alert("saved");
return alert("not saved");
});
或異步版本
dialog.showSaveDialog( {
title: "Save file",
filters: [ { name:"png pictures", ext: [ "png" ] } ], // what kind of files do you want to see when this box is opend, ( users will be able to save this kind of files )
defaultPath: app.getPath("document") // the default path to save file
}, ( filePath ) => {
if ( ! filePath ) {
// nothing was pressed
return;
}
path = filePath;
fs.writeFile( path , text , ( err , buf ) => {
if ( err )
return alert("saved");
return alert("not saved");
});
});
你快到了。 您需要通過回調等待對話的結果。 檢查文檔。
所以像:
let path;
function saveProjectAs(text) {
var options = {
title: "Save project as ",
message: "Save project as ",
nameFieldLabel: "Project Name:",
// defaultPath: directory to show (optional)
}
dialog.showSaveDialog(mainWindow, options, saveProjectAsCallback);
function saveProjectAsCallback(filePath) {
// if user pressed "cancel" then `filePath` will be null
if (filePath) {
// check for extension; optional. upath is a node package.
if (upath.toUnix(upath.extname(filePath)).toLowerCase() != ".json") {
filePath = filePath + ".json"
}
path = filePath;
fs.writeFile(path, text, (err) => {
if(err){
alert("An error ocurred creating the file "+ err.message)
}
alert("The file has been succesfully saved");
});
}
}
}
這對我有用:
const { dialog } = require('electron')
dialog.showSaveDialog({
title: "Save file"
}).then((filePath_obj)=>{
if (filePath_obj.canceled)
console.log("canceled")
else
console.log('absolute path: ',filePath_obj.filePath);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.