Deno似乎以文本文件为目标,但我也需要为网站提供图像文件。
发布于 2020-07-03 13:48:29
基本上,您只需要为您的图像类型设置正确的头文件,并以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);发布于 2020-06-05 00:01:10
您可以使用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来访问该图像
https://stackoverflow.com/questions/62199041
复制相似问题