简体   繁体   中英

deno - how to serve images

I want to serve an image in deno. I'm using the following code (simplified to be easier to read). If I try it on a textfile and set the contenttype to text/plain it works perfectly fine. If I try it with an image, it does send the content of the file but for some reason the browser tells me the file contains errors. Any Idea why that is? (I'm completely new to deno so it might be something really obvious.)

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 });
}

You're using readFileStr which should only be used for text files, since the content is converted to a UTF-8 string. For working with binary files, such as images, you need to use 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 works for text files too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM