Nodejs koa2读取服务器图片返回给前端直接展示

Posted 阴翳公子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Nodejs koa2读取服务器图片返回给前端直接展示相关的知识,希望对你有一定的参考价值。

参考:https://blog.csdn.net/lihefei_coder/article/details/105435358

const fs = require(‘fs‘);
const path = require(‘path‘);
const mime = require(‘mime-types‘); //需npm安装
const Koa = require(‘koa‘); //需npm安装
const app = new Koa();

app.use(async (ctx) => {

	let filePath = path.join(__dirname, ctx.url); //图片地址
	let file = null;
	try {
	    file = fs.readFileSync(filePath); //读取文件
	} catch (error) {
		//如果服务器不存在请求的图片,返回默认图片
	    filePath = path.join(__dirname, ‘/images/default.png‘); //默认图片地址
	    file = fs.readFileSync(filePath); //读取文件	    
	}

	let mimeType = mime.lookup(filePath); //读取图片文件类型
	ctx.set(‘content-type‘, mimeType); //设置返回类型
	ctx.body = file; //返回图片

});

  

 

以上是关于Nodejs koa2读取服务器图片返回给前端直接展示的主要内容,如果未能解决你的问题,请参考以下文章