您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

nodejs-如何读取和输出jpg图像?

nodejs-如何读取和输出jpg图像?

这是您读取整个文件内容方法,如果成功完成,则启动一个Web服务器,该Web服务器响应每个请求显示JPG图像:

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

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err // Fail if the file can't be read.
  http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    res.end(data) // Send the file data to the browser.
  }).listen(8124)
  console.log('Server running at http://localhost:8124/')
})

请注意,服务器由“ readFile”回调函数启动,并且响应标头具有Content-Type: image/jpeg

您甚至可以将image<img>数据URI源一起直接嵌入HTML页面中。例如:

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<html><body><img src="data:image/jpeg;base64,')
  res.write(Buffer.from(data).toString('base64'));
  res.end('"/></body></html>');
Node 2022/1/1 18:14:29 有496人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶