首页 > 解决方案 > 如何将上传文件的类型转换为 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. 我只想在我的服务器中指定允许的类型,那么如何在不硬编码的情况下将当前上传的图像类型放入我的服务器MediaTypeMediaType('image', 'png')

标签: node.jshttpflutterdart

解决方案


推荐阅读