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

时间:2020-11-07 16:00:29   收藏:0   阅读:27

参考: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; //返回图片

});

  

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!