如何在下一个js中访问不在public文件夹中的文件

问题描述 投票:0回答:1

我正在开发下一个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

javascript next.js file-upload
1个回答
0
投票

我明白了。只需要以不同的方式发送响应即可。

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

© www.soinside.com 2019 - 2024. All rights reserved.