node.js 将图像写入本地服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5294470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing image to local server
提问by Mark
Update
更新
The accepted answer was good for last year but today I would use the package everyone else uses: https://github.com/mikeal/request
去年接受的答案很好,但今天我会使用其他人使用的包:https: //github.com/mikeal/request
Original
原来的
I'm trying to grab google's logo and save it to my server with node.js.
我正在尝试获取 google 的徽标并使用 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!');
});
});
});
How can I get this working?
我怎样才能让它工作?
回答by Ricardo Tomasi
A few things happening here:
这里发生了一些事情:
- I assume you required fs/http, and set the dir variable :)
- google.com redirects to www.google.com, so you're saving the redirect response's body, not the image
- 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
- since you're getting binary data, you have to set the encoding accordingly on response and writeFile (default is utf8)
- 我假设您需要 fs/http,并设置 dir 变量:)
- google.com 重定向到 www.google.com,因此您保存的是重定向响应的正文,而不是图像
- 响应是流式传输的。这意味着“数据”事件会触发多次,而不是一次。您必须保存并将所有块连接在一起才能获得完整的响应正文
- 由于您正在获取二进制数据,因此您必须在 response 和 writeFile 上相应地设置编码(默认为 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.')
})
})
})
回答by m4tm4t
This thread is old but I wanted to do same things with the https://github.com/mikeal/requestpackage.
这个线程很旧,但我想用https://github.com/mikeal/request包做同样的事情。
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!");
});
});
回答by Drasill
I suggest you use http-request, so that even redirects are managed.
我建议您使用http-request,以便甚至可以管理重定向。
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);
}
});
回答by yuqin
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.')
})
})
回答by BlackBeard
Cleanestway of saving image locally using request:
使用request在本地保存图像的最干净方式:
const request = require('request');
request('http://link/to/your/image/file.png').pipe(fs.createWriteStream('fileName.png'))
If you need to add authentication tokenin 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'))
回答by Under-qualified NASA Intern
I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)
我有一个更简单的解决方案 fs.readFileSync(./my_local_image_path.jpg)
This is for reading images from Azure Cognative Services's Vision API
这是用于从Azure 认知服务的 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);

