我有一些代码:
var target = '/image/5CXfX.png'; //For example, a .PNG image
//Testing with text/html and text/plain and image/png
res.setHeader( 'Content-Type', 'image/png' );//res is response of current request
http.get( url.parse( target ), function( response ) {
var data;
response.on( 'data', function( chunk ) {
if( !data ) data = chunk; else data += chunk;
}).on('end', function() {
res.send( data );
});
});
从target
获取数据并将其显示到浏览器,取决于我设置的Content-Type
。到目前为止,它在获取文档并将其显示为 HTML 或纯文本方面运行良好。但是,当将目标更改为直接图像 URL 时,请将 Content-Type
更改为相应的文件类型(例如 image/png
或 image/jpeg
),图像已损坏。即使当我尝试下载图像时,其大小(内容长度)与原始大小一样,但没有程序可以打开它,因为它已损坏。我不太确定它如何处理文本和 html,但不能处理图像(即使 Content-Type
已正确设置)?
最佳答案
除非您因某种原因确实需要缓冲它,否则您应该只通过管道传输响应。示例:
var target = '/image/5CXfX.png';
http.get(target, function(response) {
if (response.statusCode === 200) {
res.setHeader('Content-Type', 'image/png');
return response.pipe(res);
}
// drain the response and discard it
response.resume();
res.send(response.statusCode);
});
关于javascript - 读取远程文件,并输出到浏览器。处理文本和 html。不要使用图像。 NodeJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26073183/