mirror of
https://github.com/labring/FastGPT.git
synced 2025-08-06 07:28:56 +00:00
4.6.3-website dataset (#532)
This commit is contained in:
@@ -2,8 +2,8 @@ import type { NextApiRequest, NextApiResponse } from 'next';
|
||||
import { jsonRes } from '@fastgpt/service/common/response';
|
||||
import { connectToDatabase } from '@/service/mongo';
|
||||
import { authFileToken } from '@fastgpt/service/support/permission/controller';
|
||||
import jschardet from 'jschardet';
|
||||
import { getDownloadBuf, getFileById } from '@fastgpt/service/common/file/gridfs/controller';
|
||||
import { detect } from 'jschardet';
|
||||
import { getDownloadStream, getFileById } from '@fastgpt/service/common/file/gridfs/controller';
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
|
||||
try {
|
||||
@@ -11,24 +11,43 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse<
|
||||
|
||||
const { token } = req.query as { token: string };
|
||||
|
||||
const { fileId, teamId, tmbId, bucketName } = await authFileToken(token);
|
||||
const { fileId, bucketName } = await authFileToken(token);
|
||||
|
||||
if (!fileId) {
|
||||
throw new Error('fileId is empty');
|
||||
}
|
||||
|
||||
const [file, buffer] = await Promise.all([
|
||||
const [file, encodeStream] = await Promise.all([
|
||||
getFileById({ bucketName, fileId }),
|
||||
getDownloadBuf({ bucketName, fileId })
|
||||
getDownloadStream({ bucketName, fileId })
|
||||
]);
|
||||
|
||||
const encoding = jschardet.detect(buffer)?.encoding;
|
||||
// get encoding
|
||||
let buffers: Buffer = Buffer.from([]);
|
||||
for await (const chunk of encodeStream) {
|
||||
buffers = Buffer.concat([buffers, chunk]);
|
||||
if (buffers.length > 10) {
|
||||
encodeStream.abort();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const encoding = detect(buffers)?.encoding || 'utf-8';
|
||||
|
||||
res.setHeader('Content-Type', `${file.contentType}; charset=${encoding}`);
|
||||
res.setHeader('Cache-Control', 'public, max-age=3600');
|
||||
res.setHeader('Content-Disposition', `inline; filename="${encodeURIComponent(file.filename)}"`);
|
||||
|
||||
res.end(buffer);
|
||||
const fileStream = await getDownloadStream({ bucketName, fileId });
|
||||
|
||||
fileStream.pipe(res);
|
||||
|
||||
fileStream.on('error', () => {
|
||||
res.status(500).end();
|
||||
});
|
||||
fileStream.on('end', () => {
|
||||
res.end();
|
||||
});
|
||||
} catch (error) {
|
||||
jsonRes(res, {
|
||||
code: 500,
|
||||
|
Reference in New Issue
Block a user