0

suppose you have to upload image to the Server using MultipartFile for a single key like "image". you can easily can do it but if you have different types of keys for file like "image", "logo", "banner" etc so how can you handle this for different types keys..

it is working for single key like "image"

final request = http.MultipartRequest('PUT', url,);
    request.fields.addAll(body.toMap());

    request.headers.addAll(headers);
    if (body.image.isNotEmpty) {
      final file = await http.MultipartFile.fromPath('image', body.image);
      request.files.add(file);
    }
Ali
  • 5
  • 4
  • Does this help you? https://stackoverflow.com/questions/52501529/flutter-how-to-send-multiple-files-to-http-post – Tahir Feb 15 '23 at 08:04

1 Answers1

0

Add additional fields if needed

  request.fields['field1'] = 'value1';
  request.fields['field2'] = 'value2';

full code

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

uploadImage(File imageFile) async {
  final url = 'http://example.com/upload-image';
  var request = http.MultipartRequest('POST', Uri.parse(url));

  // Create a MultipartFile from the image file
  var image = await http.MultipartFile.fromPath('image', imageFile.path);

  // Attach the MultipartFile to the MultipartRequest
  request.files.add(image);

  // Add additional fields if needed
  request.fields['field1'] = 'value1';
  request.fields['field2'] = 'value2';

  // Send the MultipartRequest to the server
  var response = await request.send();

  // Check the response status code
  if (response.statusCode == 200) {
    // Image upload successful
    print('Image uploaded successfully');
  } else {
    // Image upload failed
    print('Image upload failed with status ${response.statusCode}');
  }
}

I think this will help you

Kasun Hasanga
  • 1,626
  • 4
  • 15
  • 35