How can I send a file from either route.ts or page.ts? The file could be located anywhere in the file-system.
I am currently using this code in python + flask in the back-end...
@app.route("/thumbnail/<string:filename>")
def get_file(filename):
pathname = os.path.join(session['uploadpath'], filename)
return send_file(pathname)
to deliver images to the browser - in response to the HTML+jinja code...
<img src="/thumbnail/{{file}}" style="height:40px"/>
This allowed me to deliver images from anywhere in the file-system.
Alternately, I am also able create an image in memory and send it as a file without having to save it.
@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')
Now, I need to migrate my back-end. The client wants me to use only nextjs and am unable to find the equivalent of send_file. In nextjs, I am unable to get files from outside the public folder.
Please help me to resolve this problem - How can I send_file in nextjs?
I have tried...
res.setHeader('Content-Type', 'image/jpg')
const imageStream = createReadStream(file)
pipeline(imageStream, res, (error) => {
console.log(error);
})
and
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)
}
and
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;
}
Googling turned up these code-snippets but...
pipelineis but did you try to useimageStream.pipe(res)?fs.readFileworks...also "I've tried" isn't very helpful, tell us what happened when you tried that code.