You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js实现Flask send_file功能:从任意路径发送文件

如何在route.ts或page.ts中发送文件?文件可位于文件系统的任意位置。

我此前在后端使用python + flask,代码如下:

@app.route("/thumbnail/<string:filename>")
def get_file(filename):
    pathname = os.path.join(session['uploadpath'], filename)
    return send_file(pathname)

这段代码用于向浏览器交付图片,对应的HTML+jinja代码为:

<img src="/thumbnail/{{file}}" style="height:40px"/>

这让我可以从文件系统的任意位置交付图片。

此外,我还可以在内存中创建图片并直接作为文件发送,无需保存:

@app.route("/textimg")
def get_file(filename):
    img = Image.new('RGB',(120,40), color='red')
    fnt = ImageFont.truetype(app.root_path + '/FONTNAME.TTF', 36)
    d = ImageDraw.Draw(img)
    d.text((10,0), '123456', font=fnt, fill=(255,255,0))

    img_io = BytesIO()
    img.save(img_io, 'JPEG', quality=70)
    img_io.seek(0)
    
    return send_file(img_io, mimetype='image/jpeg')

现在我需要迁移后端,客户要求仅使用Next.js,但我找不到send_file的等效方法。在Next.js中,我无法访问public文件夹外的文件。

请帮助我解决这个问题——如何在Next.js中实现send_file的功能?

我已经尝试过以下代码片段:

res.setHeader('Content-Type', 'image/jpg')
const imageStream = createReadStream(file)
pipeline(imageStream, res, (error) => {
    console.log(error);
})

以及:

import fs from 'fs'
import path from 'path'

const filePath = path.resolve('.', 'images_folder/next.jpg')
const imageBuffer = fs.readFileSync(filePath)

export default function(req, res) {
  res.setHeader('Content-Type', 'image/jpg')
  res.send(imageBuffer)
}

还有:

import { ImageResponse } from "next/server";

export default async function get_file(req, res) {
  const filename = req.query.filename;
  const pathname = os.path.join(session['uploadpath'], filename);

  const imageResponse = new ImageResponse(pathname);
  imageResponse.headers.set("Content-Type", "image/png");

  return imageResponse;
}

我通过谷歌搜索找到了这些代码片段,但……


内容的提问来源于stack exchange,提问作者gajdhir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:16:05