node.js 从 url 下载图片

node.js download image from url

我的问题是从 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.

    });
}

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

您可以查看响应的状态码。如果是 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);
        }
    });
}

现在请求模块已被弃用,因此它不会提供更多帮助

尝试像下面这样使用 url 模块

我正在下载或发送图像以响应来自 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)
    }
  }