node.js从url下载图像

时间:2015-06-28 22:50:31

标签: javascript node.js q

我的问题是来自网址的具有未知扩展名的下载图片(可能是jpg,或png,或jpeg,或bmp)。 所以我想检查图像的Content-Length,如果它大于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.

    });
}

我正在使用Node.js的Q promises模块来避免回调地狱,但有人可以帮我检查图像大小并将其保存到文件中吗?

2 个答案:

答案 0 :(得分:3)

您可以查看回复的状态代码。如果它是200,则图像被提取没有问题。

您可以使用文件扩展名数组和递归方法按顺序尝试每个文件扩展名。使用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);
        }
    });
}

答案 1 :(得分:0)

现在不建议使用请求模块,因此它无济于事

尝试使用以下波纹管网址模块

我正在下移或发送图片以响应从url查询详细信息

const fs = require('fs');
const url = require('url')

download_image: async (req, res) => {


    let query = url.parse(req.url, true).query;
    let pic = query.image;
    let id = query.id

    let directory_name = "tmp/daily_gasoline_report/" + id + "/" + pic

    let filename = fs.existsSync(directory_name);

    if (filename) {

        //read the image using fs and send the image content back in the response
        fs.readFile(directory_name, function (err, content) {
            if (err) {
                res.writeHead(400, { 'Content-type': 'text/html' })
                console.log(err);
                res.end("No such image");
            } else {
                //specify the content type in the response will be an image
                res.writeHead(200);
                res.end(content);
            }
        });
    } else {
        logger.warn(error.NOT_FOUND)
        return res.status(401).send(error.NOT_FOUND)
    }
  }