2016-11-11 68 views
0

我正嘗試使用Node.JS下載Facebook個人資料圖片,但我遇到問題,因爲Facebook做了重定向。Node.JS將文件下載到服務器之後的重定向

網址:https://graph.facebook.com/userId/picture?type=large

我的下載功能:

var fs = require('fs'); 
var https = require('follow-redirects').https; 

var download = function(uri, filename) { 
    var deferred = Q.defer(); 

    var data = ""; 
    https.get(uri, function(response) { 
     response.on('data', function(chunk) { 
      console.log(chunk); 
      data += chunk; 
     }); 

     response.on('end', function() { 
      fs.writeFile(filename, data, 'binary', function(err) { 
       if(err) { 
        console.log(err.message); 
       } else { 
        deferred.resolve(); 
       } 
      }) 
     }); 

    }).on('error', function(err) { 
     fs.unlink(filename); 
     deferred.reject(err); 
    }); 

    return deferred.promise; 
}; 

我只得到一個大塊,所以造成文件損壞。

我該如何解決這個問題?

回答

1

試試這個:

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

function download(uri, filename) { 
    var protocol = url.parse(uri).protocol.slice(0, -1); 
    var deferred = Q.defer(); 
    var onError = function (e) { 
     fs.unlink(filename); 
     deferred.reject(e); 
    } 
    require(protocol).get(uri, function(response) { 
     if (response.statusCode >= 200 && response.statusCode < 300) { 
      var fileStream = fs.createWriteStream(filename); 
      fileStream.on('error', onError); 
      fileStream.on('close', deferred.resolve); 
      response.pipe(fileStream); 
     } else if (response.headers.location) { 
      deferred.resolve(download(response.headers.location, filename)); 
     } else { 
      deferred.reject(new Error(response.statusCode + ' ' + response.statusMessage)); 
     } 
    }).on('error', onError); 
    return deferred.promise; 
}; 
+0

謝謝,這對我的工作! –