【问题标题】:How to serve images using deno's oak?如何使用 deno 的橡树提供图像?
【发布时间】:2021-07-20 16:48:16
【问题描述】:

Deno 似乎针对文本文件,但我还需要为网站提供图像文件。

【问题讨论】:

    标签: deno oak


    【解决方案1】:

    基本上,您只需为您的图像类型设置正确的标题,并将图像数据作为Unit8Array 提供:

    在您的中间件中:

    app.use(async (ctx, next) => {
      // ...
      const imageBuf = await Deno.readFile(pngFilePath);
      ctx.response.body = imageBuf;
      ctx.response.headers.set('Content-Type', 'image/png');
    });
    

    这是一个完整的工作示例,它将下载示例图像(the digitized version of the hand-drawn deno logo) 并在http://localhost:8000/image 提供它,并在所有其他地址显示“Hello world”。运行选项在第一行的注释中:

    server.ts

    // deno run --allow-net=localhost:8000,deno.land --allow-read=deno_logo.png --allow-write=deno_logo.png server.ts
    
    import {Application} from 'https://deno.land/x/oak@v5.3.1/mod.ts';
    import {exists} from 'https://deno.land/std@0.59.0/fs/exists.ts';
    
    // server listen options
    const listenOptions = {
      hostname: 'localhost',
      port: 8000,
    };
    
    // sample image
    const imageFilePath = './deno_logo.png';
    const imageSource = 'https://deno.land/images/deno_logo.png';
    
    const ensureLocalFile = async (localPath: string, url: string): Promise<void> => {
      const fileExists = await exists(localPath);
      if (fileExists) return;
      console.log(`Downloading ${url} to ${localPath}`);
      const response = await fetch(url);
      if (!response.ok) throw new Error('Response not OK');
      const r = response.body?.getReader;
      const buf = new Uint8Array(await response.arrayBuffer());
      await Deno.writeFile(imageFilePath, buf);
      console.log('File saved');
    };
    
    await ensureLocalFile(imageFilePath, imageSource);
    
    const app = new Application();
    
    app.use(async (ctx, next) => {
      // only match /image
      if (ctx.request.url.pathname !== '/image') {
        await next(); // pass control to next middleware
        return;
      }
    
      const imageBuf = await Deno.readFile(imageFilePath);
      ctx.response.body = imageBuf;
      ctx.response.headers.set('Content-Type', 'image/png');
    });
    
    // default middleware
    app.use((ctx) => {
      ctx.response.body = "Hello world";
    });
    
    // log info about server
    app.addEventListener('listen', ev => {
      const defaultPortHttp = 80;
      const defaultPortHttps = 443;
      let portString = `:${ev.port}`;
    
      if (
        (ev.secure && ev.port === defaultPortHttps)
        || (!ev.secure && ev.port === defaultPortHttp)
      ) portString = '';
    
      console.log(`Listening at http${ev.secure ? 's' : ''}://${ev.hostname ?? '0.0.0.0'}${portString}`);
      console.log('Use ctrl+c to stop\n');
    });
    
    await app.listen(listenOptions);
    

    【讨论】:

      【解决方案2】:

      您可以使用send()

      函数send() 旨在将静态内容作为 中间件功能。在最直接的用法中,根是 提供和提供给功能的请求被满足 本地文件系统中相对于根目录的文件 请求的路径。

      const app = new Application();
      
      app.use(async (context) => {
         await send(context, context.request.url.pathname, {
            root: `${Deno.cwd()}/static`
         });
      });
      
      await app.listen({ port: 8000 });
      

      具有以下目录结构:

      static/
         image.jpg
      server.js
      

      您可以通过http://localhost:8000/image.jpg访问图片

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-20
        • 2018-12-03
        • 2013-09-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多