Sobes.tech
Junior — Middle

How can a file be included in the content of a POST request for transmission to a server?

sobes.tech AI

Answer from AI

In Flutter, to include a file in the body of a POST request, the common approach is to use the http package and send the file as part of a multipart request. This allows transmitting the file along with other data to the server.

Example of usage:

import 'package:http/http.dart' as http;
import 'dart:io';

Future<void> uploadFile(File file) async {
  var request = http.MultipartRequest('POST', Uri.parse('https://example.com/upload'));
  request.files.add(await http.MultipartFile.fromPath('file', file.path));
  var response = await request.send();
  if (response.statusCode == 200) {
    print('File uploaded successfully');
  } else {
    print('File upload error');
  }
}