DioError [DioErrorType.RESPONSE]: Http status error [404]

Viewed 7601

Postman form-data request

Request body containing

Expected Response body

Dio Flutter code

import 'package:dio/dio.dart';
import 'package:flutter_project/config/config.dart';
import '../model/postImage.dart';
import 'dart:io';



Future<PostImage> postImage(File image) async{
  String fileName = image.path.split('/').last;
  print(fileName);

  try{
    Dio dio = new Dio();
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(image.path,filename: fileName)
    });
    Map<String, String> headers= <String,String>{
      'Content-Type':'multipart/form-data'
    };
    print("${baseURL}files/upload");
    Response response = await dio.post("${baseURL}files/upload",data: formData);
    if(response.statusCode == 200){
      print("Uploaded");
    }
    else{
      print(response.data);
    }
    
  }
  catch(e){
      print(e);
  }

}

Expection that I am getting : DioError [DioErrorType.RESPONSE]: Http status error [404]

2 Answers

I added contentType: new MediaType("image", "jpeg")//in the formData. It works now.

Full Code :

import 'package:dio/dio.dart';
import 'package:flutter_project/config/config.dart';
import '../model/postImage.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';

Future<PostImage> postImage(File image) async {
  String fileName = image.path.split('/').last;
  print(fileName);

  try {
    Dio dio = new Dio();
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(
        image.path,
        filename: fileName,
        contentType: new MediaType("image", "jpeg"),
      )
    });
    Map<String, String> headers = <String, String>{
      'Content-Type': 'multipart/form-data'
    };
    print("${baseURL}files/upload");
    Response response =
        await dio.post("${baseURL}files/upload", data: formData);
    if (response.statusCode == 200) {
      print("Uploaded");
    } else {
      print(response.data);
    }
    print('Out');
  } catch (e) {
    print(e);
  }
}

When I encountered an HTTP 4xx error while using Dio and I was sure I had my Authorization set, what I did to make it work is to set the Options() parameter explicitly. Precisely, I set the method type (for a get request) and authorisation token like this: Dio().get(url, options: Options(method: "GET", headers: { "Authorization": "Bearer ${LocalStorage().getString(Keys.token)}", })));. You can also set content-type if need be. To make it easier, you can simply copy-paste into the headers: argument, some of the header values set in/by your postman when you make the same request using postman.

Related