我正在开发下一个js项目,我将文件存储在项目的根目录中
/uploads/qr/myimage.png
。我如何访问该项目中的该文件。我尝试创建一条路线/api/getImg/route.js
,它将提供图像文件,并在那里写下这段代码
import fs from 'fs';
import { NextResponse } from 'next/server';
import path from 'path';
export async function GET(req) {
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
const imagePath = path.join(process.cwd(), 'uploads', 'qr', `${id}.png`);
try {
const data = fs.readFileSync(imagePath);
return NextResponse.send(data);
} catch (error) {
console.error(error);
return NextResponse.send('Image not found');
}
}
但它给了我错误
next_dist_server_web_exports_next_response__WEBPACK_IMPORTED_MODULE_1__.default.send is not a function
我明白了。只需要以不同的方式发送响应即可。
import fs from 'fs';
import { NextResponse } from 'next/server';
import path from 'path';
export async function GET(req) {
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
try {
// Read the image file from the uploads/qr directory
const imagePath = path.join(process.cwd(), 'uploads', 'qr', `${id}.png`);
const fileContents = fs.readFileSync(imagePath);
return new NextResponse(fileContents, { status: 200, headers: new Headers({ "content-type": "image/png", }) })
} catch (error) {
console.error('Error serving image:', error);
return NextResponse.json(error)
}
}