skip to Main Content

How to upload multiple FilePicker files in Flutter web app? I have a list of File Picker Result and would like to upload to our server. My colleagues has completed an api for me to upload files and is proved working in PostMan:

enter image description here

I make use of FilePicker class to allow the user to select multiple files to upload

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("Testing"),
      ),
      body: Center(
        child: Column(
          children: [
            TextButton(
              onPressed: () async{
                FileList = await FilePicker.platform.pickFiles(allowMultiple: true);
                if (FileList != null) {
                  for(var i = 0; i < FileList!.count; i++) {
                    print(FileList!.files[i].name);
                  }
                } else {
                  // User canceled the picker
                }
              },
              child: Text('select files'),
            ),
            TextButton(
              onPressed: () async{

                // what to do here?

              },
              child: Text('upload'),
            ),
          ],
        ),
      ),
    );
  }

2

Answers


  1. To upload multiple files from a Flutter web app using FilePicker, you can use the http package to make a POST request to your server’s API. Here’s how you can modify your code to achieve that:

    Import the http package at the top of your file:

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

    Create a function that will send a POST request to your server’s API with the selected files:

    Future<void> uploadFiles(List<FilePickerResult> files) async {
      // Create a multipart request
      var request = http.MultipartRequest(
        'POST',
        Uri.parse('https://example.com/upload'),
      );
    
      // Add each file to the request as a separate part
      for (var file in files) {
        request.files.add(await http.MultipartFile.fromPath(
          'files',
          file.files.single.path!,
        ));
      }
    
      // Send the request
      var response = await request.send();
    
      // Check the response status code
      if (response.statusCode == 200) {
        print('Files uploaded successfully!');
      } else {
        print('Failed to upload files');
      }
    }
    

    Call the uploadFiles function when the "Upload" button is pressed:

        TextButton(
      onPressed: () async {
        if (FileList != null) {
          await uploadFiles(FileList!.files);
        } else {
          // User canceled the picker
        }
      },
      child: Text('upload'),
    ),
    
    Login or Signup to reply.
  2. You can add the files to the MutliPartFile list as you have to send the images in FormData format.

    void pickFiles() async {
        final result = await FilePicker.platform.pickFiles(
          allowMultiple: true,
          type: FileType.custom,
          allowedExtensions: ['jpg', 'png', 'pdf', 'doc'],
        );
      if (result != null) {
      List<MultipartFile> files = result.files
          .map((file) => MultipartFile.fromBytes(
                file.bytes as List<int>,
                filename: file.name,
              ))
          .toList();
    
      var formData = FormData.fromMap({
        'id': '',
        'type': '',
        'docType': '',
        'files': files,
      });
      for (var element in formData.files) {
        print(element.value.filename);
      }
    }
    

    Pass the formData to the API calls in the body.

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