javascript node.js 从 url 下载图片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31105574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js download image from url
提问by MeetJoeBlack
My issue is download image with unknown extenstion(it maybe jpg ,or png ,or jpeg, or bmp) from url. So I want to check Content-Length of the image and if it bigger then 0, download it to file,else try download image with another extension and etc.
我的问题是从 url 下载具有未知扩展名的图像(可能是 jpg ,或 png ,或 jpeg 或 bmp)。所以我想检查图像的内容长度,如果它大于 0,则将其下载到文件中,否则尝试使用另一个扩展名等下载图像。
var fs = require('fs');
var request = require('request');
var xml2js = require('xml2js');
var Q = require('q');
var baseUrl = 'http://test.com/uploads/catalog_item_image_main/';
Q.nfcall(fs.readFile, "./test.xml", "utf8")
.then(parseSrting)
.then(parseProductsAsync)
.then(processProductsAsync)
;
function parseSrting(data){
return Q.nfcall(xml2js.parseString,data);
}
function parseProductsAsync(xmljsonresult){
return xmljsonresult.product_list.product;
}
function processProductsAsync(products){
products.map(function(product){
var filename = product.sku + ""; // - where is image name
filename = filename.replace(/\//g, '_');
console.log('Processing file ' + filename);
var imageUrl = baseUrl + filename + '_big.'; // + image extension
//There I want to check Content-Length of the image and if it bigger then 0, download it to file,
//else try download image with another extension and etc.
});
}
I am using Q promises module for Node.js to avoid callbacks hell, but can someone help me with checking image size and save it to file?
我正在使用 Node.js 的 Q promises 模块来避免回调地狱,但是有人可以帮助我检查图像大小并将其保存到文件中吗?
回答by Ivy Jha
You can check the status code of the response. If it was 200, the image was fetched with no problems.
您可以检查响应的状态代码。如果是 200,则图像被提取没有问题。
You can use an array of file extensions and a recursive method to try each file extension in sequence. Using the request
module you can do it like this:
您可以使用文件扩展名数组和递归方法按顺序尝试每个文件扩展名。使用该request
模块,您可以这样做:
function processProductsAsync(products){
products.map(function(product){
var filename = product.sku + ""; // - where is image name
filename = filename.replace(/\//g, '_');
console.log('Processing file ' + filename);
var imageUrl = baseUrl + filename + '_big.'; // + image extension
fetchImage(imageUrl, filename, 0);
});
function fetchImage(url, localPath, index) {
var extensions = ['jpg', 'png', 'jpeg', 'bmp'];
if (index === extensions.length) {
console.log('Fetching ' + url + ' failed.');
return;
}
var fullUrl = url + extensions[index];
request.get(fullUrl, function(response) {
if (response.statusCode === 200) {
fs.write(localPath, response.body, function() {
console.log('Successfully downloaded file ' + url);
});
}
else {
fetchImage(url, localPath, index + 1);
}
});
}