How to serve an image using nodejs

前端 未结 11 1253
渐次进展
渐次进展 2020-11-22 08:18

I have a logo that is residing at the public/images/logo.gif. Here is my nodejs code.

http.createServer(function(req, res){
  res.writeHead(200,          


        
相关标签:
11条回答
  • 2020-11-22 09:08

    It is too late but helps someone, I'm using node version v7.9.0 and express version 4.15.0

    if your directory structure is something like this:

    your-project
       uploads
       package.json
       server.js
    

    server.js code:

    var express         = require('express');
    var app             = express();
    app.use(express.static(__dirname + '/uploads'));// you can access image 
     //using this url: http://localhost:7000/abc.jpg
    //make sure `abc.jpg` is present in `uploads` dir.
    
    //Or you can change the directory for hiding real directory name:
    
    `app.use('/images', express.static(__dirname+'/uploads/'));// you can access image using this url: http://localhost:7000/images/abc.jpg
    
    
    app.listen(7000);
    
    0 讨论(0)
  • 2020-11-22 09:09

    //This method involves directly integrating HTML Code in the res.write
    //first time posting to stack ...pls be kind
    
    const express = require('express');
    const app = express();
    const https = require('https');
    
    app.get("/",function(res,res){
        res.write("<img src="+image url / src +">");
        res.send();
    });
    
    app.listen(3000, function(req, res) {
      console.log("the server is onnnn");
    });

    0 讨论(0)
  • 2020-11-22 09:12

    var http = require('http');
    var fs = require('fs');
    
    http.createServer(function(req, res) {
      res.writeHead(200,{'content-type':'image/jpg'});
      fs.createReadStream('./image/demo.jpg').pipe(res);
    }).listen(3000);
    console.log('server running at 3000');
    
    0 讨论(0)
  • 2020-11-22 09:12

    I like using Restify for REST services. In my case, I had created a REST service to serve up images and then if an image source returned 404/403, I wanted to return an alternative image. Here's what I came up with combining some of the stuff here:

    function processRequest(req, res, next, url) {
        var httpOptions = {
            hostname: host,
            path: url,
            port: port,
            method: 'GET'
        };
    
        var reqGet = http.request(httpOptions, function (response) {
            var statusCode = response.statusCode;
    
            // Many images come back as 404/403 so check explicitly
            if (statusCode === 404 || statusCode === 403) {
                // Send default image if error
                var file = 'img/user.png';
                fs.stat(file, function (err, stat) {
                    var img = fs.readFileSync(file);
                    res.contentType = 'image/png';
                    res.contentLength = stat.size;
                    res.end(img, 'binary');
                });
    
            } else {
                var idx = 0;
                var len = parseInt(response.header("Content-Length"));
                var body = new Buffer(len);
    
                response.setEncoding('binary');
    
                response.on('data', function (chunk) {
                    body.write(chunk, idx, "binary");
                    idx += chunk.length;
                });
    
                response.on('end', function () {
                    res.contentType = 'image/jpg';
                    res.send(body);
                });
    
            }
        });
    
        reqGet.on('error', function (e) {
            // Send default image if error
            var file = 'img/user.png';
            fs.stat(file, function (err, stat) {
                var img = fs.readFileSync(file);
                res.contentType = 'image/png';
                res.contentLength = stat.size;
                res.end(img, 'binary');
            });
        });
    
        reqGet.end();
    
        return next();
    }
    
    0 讨论(0)
  • 2020-11-22 09:14

    This method works for me, it's not dynamic but straight to the point:

    const fs      = require('fs');
    const express = require('express');
    const app     = express();
    
    app.get( '/logo.gif', function( req, res ) {
    
      fs.readFile( 'logo.gif', function( err, data ) {
    
        if ( err ) {
    
          console.log( err );
          return;
        }
    
        res.write( data );
        return res.end();
      });
    
    });
    
    app.listen( 80 );
    
    0 讨论(0)
提交回复
热议问题