我在构建一个应用程序来将图像从带有 multipartrequest 的 flutter 应用程序上传到带有 nodejs 和 multer 的服务器时遇到问题。
这是我的代码和错误消息:
颤动:
print("TEST1");
var request =
http.MultipartRequest("POST", Uri.parse(url));
print("TEST2");
request.fields['request'] =
jsonEncode(<String, int>{'todoId': todoId});
print("TEST3");
try {
File file =
await File.fromRawPath(result.files.single.bytes!);
print("TEST4");
http.MultipartFile file_forrequest =http.MultipartFile('filetoupload',
file.readAsBytes().asStream(), file.lengthSync(),
filename: file.path.split("/").last);
request.files.add(file_forrequest);
} catch (e) {
print("ERROR: " + e.toString());
}
print("TEST5");
request.headers.addAll(<String, String>{
"Authorization": "Bearer " + token.toString(),
"Content-Type": "application/json"
});
print("TEST6");
var response = await request.send();
print("TEST7");
print(response.statusCode);
String res = await response.stream.bytesToString();
print(res);
nodejs代码:
app.post(`${vorPath}/otherFileToToDo`, jsonParser, berechtigungmitgruppepruefen, uploadFileToDo("filetoupload"), async (req, res) => {
console.log("FILES:");
console.log(req.files);
console.log("__");
const request = JSON.parse(req.body.request);
const todoId = request.todoId;
const peopleId = req.user.peopleId;
const filePath = req.file.path;
try {
const todos = await prisma.todos.findMany({
where: {
id: todoId,
zustaendige: {
some: {
peopleId: peopleId
}
}
}
});
if (todos.length == 1) {
const todo = todos[0];
const otherFilesPaths = todo.otherFilesPaths;
otherFilesPaths.push(filePath);
await prisma.todos.update({
where: {
id: todoId
},
data: {
otherFilesPaths: otherFilesPaths
}
})
res.sendStatus(200);
} else {
const todos_2 = await prisma.todos.findMany({
where: {
id: todoId
}
})
if (todos_2.length == 1) {
res.sendStatus(401);
} else {
res.sendStatus(404);
}
}
} catch (error) {
console.log("ERROR: " + error);
res.sendStatus(500);
}
res.sendStatus(200);
})
这里是使用的函数uploadFileToDo的代码:
function uploadFileToDo(file) {
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, '/mnt/sknasserver/todofiles/');
},
filename: (req, file, cb) => {
const withoutLastFour = file.originalname.slice(0, -4);
const lastFour = file.originalname.slice(-4);
const newFileName = withoutLastFour + "-" + password_generator.generate({
length: 10,
symbols: false,
numbers: true
}) + lastFour;
cb(null, newFileName);
},
});
const upload = multer({ storage: storage });
const uploadsingle = upload.single(file);
return (req, res, next) => {
uploadsingle(req, res, (err) => {
if (err) {
console.error('Error during file upload:', err);
return res.status(400).send('Error during file upload: ' + err.message);
}
console.log('File uploaded successfully:', req.file);
req.file.path = "/todofiles/" + req.file.filename;
next();
});
};
}
服务器控制台的输出:
file
App listening on port 5000
null
File uploaded successfully: undefined
/home/schemannkurier/api/sk_backend/api.js:108
req.file.path = "/todofiles/" + req.file.filename;
^
TypeError: Cannot read properties of undefined (reading 'filename')
at /home/schemannkurier/api/sk_backend/api.js:108:54
at done (/home/schemannkurier/api/sk_backend/node_modules/multer/lib/make-middleware.js:45:7)
at indicateDone (/home/schemannkurier/api/sk_backend/node_modules/multer/lib/make-middleware.js:49:68)
at Multipart.<anonymous> (/home/schemannkurier/api/sk_backend/node_modules/multer/lib/make-middleware.js:166:7)
at Multipart.emit (node:events:514:28)
at Multipart.emit (node:domain:488:12)
at emitCloseNT (node:internal/streams/destroy:132:10)
at process.processTicksAndRejections (node:internal/process/task_queues:81:21)
Node.js v20.10.0
flutter 调试控制台中的输出:
TEST1
TEST2
TEST3
TEST4
ERROR: Unsupported operation: _Namespace
TEST5
TEST6
TEST7
502
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.25.5</center>
</body>
</html>
6
<!-- a padding to disable MSIE and Chrome friendly error page -->
顺便说一句,在邮递员中,路线可以使用该参数:
请帮助我,我尝试了一切......
您的问题解决了吗,在这里面临同样的问题。经过多次调试,现在我得到了期望 image 的其他字段。当尝试使用 req.file 访问文件字段时,未定义。我认为图像没有从 flutter 端上传到服务器。有人帮忙 使用 Dio/Http 包从 Flutter 向 Express Server 发送视频文件和表单数据的问题,Android 手机附加调试模式