【问题标题】:deno - how to serve imagesdeno - 如何提供图像
【发布时间】:2020-06-07 21:54:49
【问题描述】:

我想在 deno 中提供图像。我正在使用以下代码(简化为更易于阅读)。如果我在文本文件上尝试它并将内容类型设置为文本/纯文本,它工作得非常好。如果我尝试使用图像,它确实会发送文件的内容,但由于某种原因,浏览器会告诉我文件包含错误。任何想法为什么会这样? (我对 deno 完全陌生,所以它可能非常明显。)

import { serve } from "https://deno.land/std/http/server.ts";
import { readFileStr } from 'https://deno.land/std/fs/read_file_str.ts';

for await (const req of serve({ port: 80 })) {
    const img = await readFileStr('./myfolder/cat.png');

    const head = new Headers();
    head.set('content-type', 'image/png');

    req.respond({ headers: head, body: img, status: 200 });
}

【问题讨论】:

    标签: javascript deno


    【解决方案1】:

    您正在使用readFileStr,它应该只用于文本文件,因为内容被转换为UTF-8 字符串。要处理二进制文件,例如图像,您需要使用Deno.readFile

    for await (const req of serve({ port: 80 })) {
        const img = await Deno.readFile('./myfolder/cat.png');
    
        const head = new Headers();
        head.set('content-type', 'image/png');
    
        req.respond({ headers: head, body: img, status: 200 });
    }
    

    Deno.readFile 也适用于文本文件。

    【讨论】:

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