在HTML按鈕:
<button onclick='myUrlSaveAs("http://www.example.com/path/to/file.jpg")'>Save As</button>
在你的JavaScript文件:
// Include in the render side
var elerem = require('electron').remote;
var dialog = elerem.dialog;
var app = elerem.app;
var http = require('http');
var fs = require('fs');
var path = require('path');
function myUrlSaveAs(remoteUrl){
// app.getPath("desktop") // User's Desktop folder
// app.getPath("documents") // User's "My Documents" folder
// app.getPath("downloads") // User's Downloads folder
var toLocalPath = path.resolve(app.getPath("desktop"), path.basename(remoteUrl)
var userChosenPath = dialog.showSaveDialog({ defaultPath: toLocalPath });
if(userChosenPath){
download (remoteUrl, userChosenPath, myUrlSaveAsComplete)
}
}
function myUrlSaveAsComplete(err){
alert("done");
}
function download (url, dest, cb) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb); // close() is async, call cb after close completes.
});
}).on('error', function(err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
if (cb) cb(err.message);
});
};
來源
2017-12-14 18:52:31
bob
謝謝您的回答。我無法使這種方法工作。我認爲我在主流程和渲染器流程中需要一些庫。在我殺死了所有節點模塊並重新安裝後,我的原始方法奏效。不確定究竟是什麼導致了問題,但現在的作品! – djsosofresh