将映像写入本地服务器 [英] Writing image to local server

查看:47
本文介绍了将映像写入本地服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新

去年接受的答案很好,但是今天我将使用其他所有人使用的软件包: https://github.com/mikeal/request

The accepted answer was good for last year but today I would use the package everyone else uses: https://github.com/mikeal/request

原始

我正在尝试获取Google的徽标,并使用node.js将其保存到我的服务器中.

I'm trying to grab google's logo and save it to my server with node.js.

这是我现在所拥有的并且不起作用:

This is what I have right now and doesn't work:

        var options = {
            host: 'google.com',
            port: 80,
            path: '/images/logos/ps_logo2.png'
        };

        var request = http.get(options);

        request.on('response', function (res) {
            res.on('data', function (chunk) {
                fs.writeFile(dir+'image.png', chunk, function (err) {
                    if (err) throw err;
                    console.log('It\'s saved!');
                });
            });
        });

我该如何工作?

推荐答案

此处发生了一些事情:

  1. 假设您需要fs/http,并设置dir变量:)
  2. google.com重定向到www.google.com,因此您要保存重定向响应的正文,而不是图像
  3. 响应是流式的.这意味着数据"事件会触发多次,而不是触发一次.您必须保存所有块并将它们连接在一起才能获得完整的响应正文
  4. 由于要获取二进制数据,因此必须在响应和writeFile上设置相应的编码(默认为utf8)

这应该有效:

var http = require('http')
  , fs = require('fs')
  , options

options = {
    host: 'www.google.com'
  , port: 80
  , path: '/images/logos/ps_logo2.png'
}

var request = http.get(options, function(res){
    var imagedata = ''
    res.setEncoding('binary')

    res.on('data', function(chunk){
        imagedata += chunk
    })

    res.on('end', function(){
        fs.writeFile('logo.png', imagedata, 'binary', function(err){
            if (err) throw err
            console.log('File saved.')
        })
    })

})

这篇关于将映像写入本地服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆