46,185 questions
使用Azure函数应用作为POSTAPI,文件始终无法被写入数组中,也没法被multer读取
Shengqi Zhang
0
Reputation points
我尝试了multer,req,fs,结果都一样,要么返回没有文件,要么显示req.pipe is not a function
const multer = require('multer');
module.exports = async function (context, req) {
context.log('HTTP trigger function processed a request.');
try {
// 使用 multer 处理文件上传
const upload = multer().single('file');
upload(req, null, async function (err) {
if (err) {
context.log.error('Error uploading file:', err.message);
context.res = {
status: 400,
body: 'Error uploading file.',
};
} else {
// 文件上传成功,可以在 req 中获取上传的文件信息
const file = req.file;
context.log('File:', file);
if (!file || !file.originalname) {
context.log.error('Invalid file object:', file);
context.res = {
status: 400,
body: 'Invalid file object.',
};
} else {
// 在这里可以添加其他需要的逻辑,例如记录文件信息等
context.res = {
status: 200,
body: `File ${file.originalname} uploaded successfully.`,
};
}
}
context.done();
});
} catch (error) {
context.log.error('Unhandled error:', error.message);
context.res = {
status: 500,
body: 'Internal Server Error.',
};
context.done();
}
};
const fs = require('fs');
module.exports = async function (context, req) {
context.log('HTTP trigger function processed a request.');
try {
if (!req.body || !req.body.file) {
context.res = {
status: 400,
body: 'No file provided in the request.',
};
} else {
const base64Data = req.body.file.replace(/^data:.*,/, '');
const binaryData = Buffer.from(base64Data, 'base64');
// 保存文件
fs.writeFileSync('path/to/save/file.jpg', binaryData);
context.res = {
status: 200,
body: 'File uploaded successfully.',
};
}
} catch (error) {
context.log.error('Unhandled error:', error.message);
context.res = {
status: 500,
body: 'Internal Server Error.',
};
}
context.done();
};
我检查到眼花也没看出来问题,是函数方程不能拿来做这个吗?POSTMAN配置也检查了很多遍,get和postkey都很顺畅,只有文件无法post
help me,please~
Community Center Not monitored
Sign in to answer