Ad

Flutter Dio Image Upload Not Working Throws Server 401 Error, But Works In Postman

- 1 answer

This is my postman request with a header Authorization Bearer Token.

I am trying to upload the image, everything is set up as mentioned with the documents dio and exactly the same as the postman parameter, but it is throwing a 401 error, it is giving me an Unauthorized error, it would appear that it is not taking the token to process and upload the file. I was reading and moving options that were mentioned in post, but unfortunately I have not been successful. I would be very grateful if someone could give me some guidance and help me to get the process done.

postman

My dio request:

employeeAttachFile(File file) async {

  final SecureStorage _secureStorage = SecureStorage();
  final token = await _secureStorage.readToken('token');

  final String uri = '${ApiPaths.basisApi}${ApiPaths.addEmployeesFile}15';

  String fileName = file.path.split('/').last;
  print(fileName);

  FormData data = FormData.fromMap({
    "file": await MultipartFile.fromFile(
      file.path,
      filename: fileName,
    ),
  });

  Dio dio = new Dio(BaseOptions(
      headers: {"Authorization": token}, contentType: "application/json"));
  await dio.post(uri, data: data).then((response) {
    var jsonResponse = jsonDecode(response.toString());
    print(jsonResponse);
  }).catchError((error) => print(error));
}

This is my error:

Error

Ad

Answer

Try

{'Authorization': 'Bearer $token'}

Ad
source: stackoverflow.com
Ad