delmin
delmin

Reputation: 2700

Uploading image to backend

I can not get image upload to my restAPI server via http package. I spend whole day looking for an answer and didn't find any. My backend require an actually image but I don't seems to manage it with http package.

  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;
    }
  }

My backend is written in node.js and was tested in postman so backend should be fine. However when I tried to upload an image from my front end it gives me error only images allowed which means the image doesn't get to the server(allowed image type is correct). Please any help appreciated

error triggered in 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);
   }
}

Upvotes: 0

Views: 262

Answers (2)

John Joe
John Joe

Reputation: 12803

That because contentType: MediaType('image', '*') will resulted as image/*, which did not matched with the file.mimetype in node.js.

Upvotes: 1

proversion
proversion

Reputation: 593

 uri = Uri.parse(url);

 var request = new MultipartRequest("PUT", uri);

 var multipartFile = await MultipartFile.fromPath("package", path);

 //path = filepath 

 request.files.add(multipartFile);

 StreamedResponse response = await request.send();

 return response;

Upvotes: 0

Related Questions