Writing image to local server

前端 未结 6 1176
孤街浪徒
孤街浪徒 2020-11-28 19:38

Update

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


相关标签:
6条回答
  • 2020-11-28 19:45

    A few things happening here:

    1. I assume you required fs/http, and set the dir variable :)
    2. google.com redirects to www.google.com, so you're saving the redirect response's body, not the image
    3. the response is streamed. that means the 'data' event fires many times, not once. you have to save and join all the chunks together to get the full response body
    4. since you're getting binary data, you have to set the encoding accordingly on response and writeFile (default is utf8)

    This should work:

    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.')
            })
        })
    
    })
    
    0 讨论(0)
  • 2020-11-28 19:46

    How about this?

    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')
    
    var chunks = [];
    
    res.on('data', function(chunk){
    
        //imagedata += chunk
        chunks.push(chunk)
    
    })
    
    res.on('end', function(){
    
        //fs.writeFile('logo.png', imagedata, 'binary', function(err){
    
        var buffer = Buffer.concat(chunks)
        fs.writeFile('logo.png', buffer, function(err){
            if (err) throw err
            console.log('File saved.')
        })
    
    })
    
    0 讨论(0)
  • 2020-11-28 19:55

    This thread is old but I wanted to do same things with the https://github.com/mikeal/request package.

    Here a working example

    var fs      = require('fs');
    var request = require('request');
    // Or with cookies
    // var request = require('request').defaults({jar: true});
    
    request.get({url: 'https://someurl/somefile.torrent', encoding: 'binary'}, function (err, response, body) {
      fs.writeFile("/tmp/test.torrent", body, 'binary', function(err) {
        if(err)
          console.log(err);
        else
          console.log("The file was saved!");
      }); 
    });
    
    0 讨论(0)
  • 2020-11-28 19:56

    I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)

    This is for reading images from Azure Cognative Services's Vision API

    const subscriptionKey = 'your_azure_subscrition_key';
    const uriBase = // **MUST change your location (mine is 'eastus')**
        'https://eastus.api.cognitive.microsoft.com/vision/v2.0/analyze';
    
    // Request parameters.
    const params = {
        'visualFeatures': 'Categories,Description,Adult,Faces',
        'maxCandidates': '2',
        'details': 'Celebrities,Landmarks',
        'language': 'en'
    };
    
    const options = {
        uri: uriBase,
        qs: params,
        body: fs.readFileSync(./my_local_image_path.jpg),
        headers: {
            'Content-Type': 'application/octet-stream',
            'Ocp-Apim-Subscription-Key' : subscriptionKey
        }
    };
    
    request.post(options, (error, response, body) => {
    if (error) {
        console.log('Error: ', error);
        return;
    }
    let jsonString = JSON.stringify(JSON.parse(body), null, '  ');
    body = JSON.parse(body);
    if (body.code) // err
    {
        console.log("AZURE: " + body.message)
    }
    
    console.log('Response\n' + jsonString);
    
    0 讨论(0)
  • 2020-11-28 20:05

    I suggest you use http-request, so that even redirects are managed.

    var http = require('http-request');
    var options = {url: 'http://localhost/foo.pdf'};
    http.get(options, '/path/to/foo.pdf', function (error, result) {
        if (error) {
            console.error(error);
        } else {
            console.log('File downloaded at: ' + result.file);
        }
    });
    
    0 讨论(0)
  • 2020-11-28 20:09

    Cleanest way of saving image locally using request:

    const request = require('request');
    request('http://link/to/your/image/file.png').pipe(fs.createWriteStream('fileName.png'))
    

    If you need to add authentication token in headers do this:

    const request = require('request');
    request({
            url: 'http://link/to/your/image/file.png',
            headers: {
                "X-Token-Auth": TOKEN,
            }
        }).pipe(fs.createWriteStream('filename.png'))                    
    
    0 讨论(0)
提交回复
热议问题