下面的motia(https://www.motia.dev/) API step 代码,用于下载指定PDF文件,目前,下载后的文件内容不对,部份如下:
{"type":"Buffer","data":[37,80,68,70,45,49,46,53,10,37,181,237,174,251,10,52,32,48,32,111,98,106,10,60,60,32,47,76,101,110,103,116,104,32,53,32,48,32,82,10,32,32,32,47,70,105,108,116,101,114,32,47,70,108,97,116,101,68,101,99,111,100,101,10,62,62,10,115,116,114,101,97,109,10,120,156,204,189,205,174,244,204,146,157,55,239,171,248,1
请解决。
下面是相应的代码:
const { z } = require('zod');
import fs from 'fs';
import path from 'path';
// 导入dotenv模块
require('dotenv').config();
// Basic app starter - JavaScript API endpoint
exports.config = {
type: 'api',
name: 'downloadFile',
description: 'Download file',
method: 'GET',
path: '/api/service/image',
emits: [],
flows: [],
};
exports.handler = async (req, { logger, emit, traceId, streams }) => {
try {
// 处理预检请求
if (req.method === 'OPTIONS') {
return {
status: 200,
body: {
}
};
}
const { path: imagePath } = req.queryParams;
logger.info('🚀 Starting basic app', { imagePath, traceId });
if (!imagePath) {
return {
status: 400,
body: {
message: '缺少图片路径参数!',
}
};
}
const fullPath = process.env.R_FILE_PREFIX + imagePath
// 验证文件是否存在
if (!fs.existsSync(fullPath)) {
return {
status: 404,
body: {
message: '图片文件不存在!',
}
};
}
// 获取文件信息
const stats = fs.statSync(fullPath);
// 创建可读流
// const fileStream = fs.createReadStream(fullPath);
const buffer = fs.readFileSync(fullPath);
// 根据扩展名确定内容类型
const ext = path.extname(fullPath).toLowerCase();
const contentType = getContentType(ext);
logger.info('download file successfully', { fullPath });
return {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Authorization',
// 'Content-Type': 'application/octet-stream', // contentType,
'Content-Type':contentType,
'Content-Disposition': `attachment; filename="${path.basename(fullPath)}"`,
'Content-Length': stats.size.toString(),
'Cache-Control': 'no-cache'
},
body: buffer
// body: fs.createReadStream(fullPath)
}
} catch (e) {
console.log('e: ', e)
}
};
// 获取内容类型
function getContentType(ext) {
const types = {
'.pdf': 'application/pdf',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.webp': 'image/webp'
};
return types[ext] || 'image/jpeg';
}
/* test
curl -OJ "http://localhost:3301/api/service/image?path=tasks/20250708064412/figure/MGCK2501-009_MGCK2504-007.snp.pdf"
http://localhost:3301/api/service/image?path=tasks%2F20250708064412%2Ffigure%2FMGCK2501-009_MGCK2504-007.snp.pdf
curl -OJ "http://localhost:3301/api/service/image?path=tasks/20250708064412/figure/MGCK2501-009_MGCK2504-007.snp.pdf"
*/