http - 上传图片到后台
问题描述
我无法通过 http 包将图像上传到我的 restAPI 服务器。我花了一整天寻找答案,但没有找到任何答案。我的后端需要一个实际的图像,但我似乎没有使用 http 包来管理它。
Future<void> createProfile(Profile profile) async {
try {
var request =
new http.MultipartRequest("POST", Uri.parse(APIPath.createProfile()));
request.fields.addAll(profile.toMap());
request.files.add(await http.MultipartFile.fromPath(
'image', profile.image.path,
contentType: MediaType('image', '*')));
request.headers['authorization'] = "Bearer $_token";
final response = await request.send();
if (response.statusCode == 200) print('Uploaded!');
notifyListeners();
} catch (error) {
throw error;
}
}
我的后端是用 node.js 编写的,并在邮递员中进行了测试,所以后端应该没问题。但是,当我尝试从前端上传图像时,它给了我错误only images allowed
,这意味着图像没有到达服务器(允许的图像类型是正确的)。请任何帮助表示赞赏
Node.js 中触发的错误
const fileFilter = (req, file, cb) => {
if (file.mimetype === 'image/png' || file.mimetype === 'image/gif' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg') {
cb(null, true);
} else {
const error = new Error('Only images are allowed')
error.statusCode = 406;
cb(error);
}
}
解决方案
那是因为contentType: MediaType('image', '*')
将导致 as与inimage/*
不匹配。file.mimetype
node.js
推荐阅读
- mysql - 如何从结果集方法返回整数
- authorization - 根据路径过滤
- javascript - SetInterval 循环直到找到元素
- javascript - 如何在一条语句中进行多个 SQL 查询(使用 Node)?
- android - 哪种 TextAppearance 样式与应用启动器图标下方的文本匹配?
- python - 为什么 beautifulsoup 没有为这张表返回任何内容?
- android - Firebase + Flutter - 云函数 onCall 导致 Android 应用出现“未经身份验证”错误
- c++ - 字符串附加擦除字符串?
- javascript - 你可以直接用 .then 调用异步函数/方法吗?
- javascript - 更改父元素比例,同时保持子元素比例正确