使用 NodeJS 从 URL 下载 JPG 时图像损坏
Corrupt image when downloading JPG from URL using NodeJS
我在 JavaScript 中创建了一个函数,它从 URL 下载图像并将图像写入磁盘。该功能适用于我下载的大多数图像,但有大约 30 张(共 400 张)已损坏且无法打开。文件已创建,但没有关联的扩展名,详细信息显示该文件为 0 kB。我知道源文件没有损坏,因为我在 C# 中有一个适用于所有文件的有效解决方案。
var download = function(url, destination, callback) {
fs.exists(destination, function(exists){
if (!exists){
http.get(url, function(response) {
var imageData = '';
response.setEncoding('binary');
response.on('data', function(chunk){
imageData += chunk;
});
response.on('end', function(){
fs.writeFile(destination, imageData, 'binary', function(error){
if(error){
console.log(error);
} else{
callback();
}
});
});
});
}
});
};
我正在 Windows 机器上工作,不确定这是否会成为问题,所以我想我会提到它。
原来我没有检查路径字符串中的非法字符。
在我的 C# 解决方案中,我使用了不同的文件名。一旦我用正则表达式删除了非法字符,一切都很好。
我在 JavaScript 中创建了一个函数,它从 URL 下载图像并将图像写入磁盘。该功能适用于我下载的大多数图像,但有大约 30 张(共 400 张)已损坏且无法打开。文件已创建,但没有关联的扩展名,详细信息显示该文件为 0 kB。我知道源文件没有损坏,因为我在 C# 中有一个适用于所有文件的有效解决方案。
var download = function(url, destination, callback) {
fs.exists(destination, function(exists){
if (!exists){
http.get(url, function(response) {
var imageData = '';
response.setEncoding('binary');
response.on('data', function(chunk){
imageData += chunk;
});
response.on('end', function(){
fs.writeFile(destination, imageData, 'binary', function(error){
if(error){
console.log(error);
} else{
callback();
}
});
});
});
}
});
};
我正在 Windows 机器上工作,不确定这是否会成为问题,所以我想我会提到它。
原来我没有检查路径字符串中的非法字符。 在我的 C# 解决方案中,我使用了不同的文件名。一旦我用正则表达式删除了非法字符,一切都很好。