我最近开始使用 NW.JS 开发桌面应用程序,我需要从 URL ( http://someurl.org/file.zip ) 下载一个文件,我设法保存了该文件,但它似乎已损坏或格式不正确,我无法打开 zip 或解压缩。
我正在使用 jQuery 从 Node.JS 下载文件和“fs”模块来保存它。
这是ajax请求:
module.exports.download = function (jQuery, url) {
return jQuery.ajax({
url : url,
timeout : 1000000
});
};
剩下的是:
$('#btnUpdateClient')
.click(function () {
ClientDownload
.download($, addresses.CLIENT_URL)
.complete(function (xhr, status) {
console.log(xhr);
fs.writeFile('./files/staClient.zip', xhr.responseText, function (err) {
if(err) {
alert('error!');
console.log(err);
} else {
alert('file Saved!');
}
});
});
});
显然缺少某些东西,.zip 文件是 3.8 MB,但是当我使用 fs.writeFile() 时,文件最终变成了 7.3 MB
我是 NW.JS 的新手,有什么建议吗?
最佳答案
如果下载进度对您很重要,请使用:
var http = require('http');
var fs = require('fs');
var req = http.get('http://someurl.org/file.zip', function (res) {
var fileSize = res.headers['content-length'];
res.setEncoding('binary');
var a = "";
res.on('data', function (chunk) {
a += chunk;
document.getElementById('percent').innerHTML = Math.round(100*a.length/fileSize) + "";
});
res.on('end', function() {
fs.writeFile('D:\\file.zip', a, 'binary', function (err) {
if (err) throw err;
console.log('finished');
});
});
});
关于jquery - NW JS - 从 URL 下载并保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31125357/