首页 > 解决方案 > 上传图片到后台

问题描述

我无法通过 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);
   }
}

标签: httpflutterdart

解决方案


那是因为contentType: MediaType('image', '*')将导致 as与inimage/*不匹配。file.mimetypenode.js


推荐阅读