node.js - 如何将上传文件的类型转换为 MediaType
问题描述
我在我的飞镖客户端使用 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', 'png'))); //<- specified png image type
request.headers['authorization'] = "Bearer $_token";
final response = await request.send();
if (response.statusCode == 200) print('Uploaded!');
notifyListeners();
return response;
} catch (error) {
throw error;
}
}
我在我的服务器端 node.js 中使用 Multer 来允许某些类型的图像
const fileFilter = (req, file, cb) => {
console.log(file.mimetype); //<-- prints image/png for jpg files
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);
}
}
我注意到,当类型的图像jpg
从我的客户端上传到服务器时,在服务器中被识别为png
指定contentType: MediaType('image', 'png')
但保存为jpg
. 我只想在我的服务器中指定允许的类型,那么如何在不硬编码的情况下将当前上传的图像类型放入我的服务器MediaType
中MediaType('image', 'png')
?
解决方案
推荐阅读
- javascript - ReactJS 切换汉堡菜单
- python - 循环将数据保存在目录中并在python上打印
- rabbitmq - 在rabbitmq中使用默认交换时,如何允许用户仅发布到特定(而不是全部)队列?
- java - 在一个 jar 中使用 Spring boot 2.x 构建 angular 11
- python - 定位 VideoCapture() 的网络摄像头设备 ID
- sql-server - SQL Server DMV(动态管理视图)未在具有 2 个索引的表上显示上次用户更新信息
- android - 如何将标识符附加到微调器项目?
- c++ - 骑士之旅问题编译没有结束
- input - 它显示系统指标的“无法解析/无效的布尔值”错误
- javascript - 错误 AttributeError:“NoneType”对象没有属性“内核”