skip to Main Content

I used to send file to server by HTTP package like this:

final request = http.MultipartRequest('POST', postUri);

      request.headers.addAll(Parameters.getHeader(User.accessToken!));

      request.files.add(multipartFile);
      final responseStream = await request.send();

but now I’m using Dio package as it gives us more tools, so I implemented it like this:

final multiPartFile = MultipartFile.fromBytes(
      result.fileContent!.readAsBytesSync(),
      filename: 'file',
    );

final result = await _httpClient.post<dynamic>(
      ApiEndPoint.fileUploadUrl,
      data: FormData.fromMap({'file': multiPartFile }),
    );

but I get 400 : Bad request, is anything wrong with dio? is any difference between sending file in dio and HTTP?

2

Answers


  1. try this

    String fileName = file.path.split('/').last;
    FormData formData = FormData.fromMap({
         "file": await MultipartFile.fromFile(file.path, filename:fileName),
    });
    
    response = await dio.post("/info", data: formData);
    
    Login or Signup to reply.
  2. Hope that Flutter Dio Multipart request example below helps you

    final formData = FormData.fromMap({
      'name': 'dio',
      'date': DateTime.now().toIso8601String(),
      'file': await MultipartFile.fromFile('./text.txt', filename: 'upload.txt'),
      'files': [
        await MultipartFile.fromFile('./text1.txt', filename: 'text1.txt'),
        await MultipartFile.fromFile('./text2.txt', filename: 'text2.txt'),
      ]
    });
    final response = await dio.post('/info', data: formData);
    

    Under ‘files’ you can send single file or array of multiple file paths. In this, I have added 2 files which are static, you may update the code according to your requirement i.e. make upload files one by one or multiple files in one go.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search