簡體   English   中英

deno - 如何提供圖像

[英]deno - how to serve images

我想在 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 });
}

您正在使用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適用於文本文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM