简体   繁体   中英

How to upload a file picked by file_picker in flutter

I need to send an attachment to an email picked by file_picker from flutter. How to send the file.

Padding(
          padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
          child: RaisedButton(
            elevation: 0,
            onPressed: () async{
              final result = await FilePicker.platform.pickFiles();
              if(result == null) return;
              final PlatformFile file = result.files.first;
              setState(() {
                qatarId = file.name;
              });
              openFile(file);
            },
            color: Colors.white,
            shape: RoundedRectangleBorder(
              side: BorderSide(
                color: Colors.green,
                width: 1),
              borderRadius: BorderRadius.all(Radius.circular(0),
              ),
            ),
            child: Padding(
              padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    'Qatar ID',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.normal,
                      color: Colors.green,
                    ),
                  ),
                  Icon(
                    Icons.upload_sharp,
                    color: Colors.green,
                  )
                ],
              ),
            ),
          ),
        ),

How I can define uploading the image. The Images are taken from file_picker.

Use dio library A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc.

          FilePickerResult? result = await FilePicker.platform.pickFiles(
                      type: FileType.custom,
                      allowedExtensions: ['jpg', 'pdf', 'doc', 'png', 'mp4', 'mkv'],
                    );
                    if (result != null) {
                      PlatformFile file = result.files.first;
                
                      print(file.name);
                      print(file.bytes);
                      print(file.size);
                      print(file.extension);
                      print(file.path);
                 var multipartFile = await MultipartFile.fromFile(file.path,
                       );
                    FormData formData = FormData.fromMap({
                
                
                
                      "MediaFile": multipartFile,  //define your json data here
                    });
            
            
             functionToUploadToServer(formData); //call upload function passing multiform data
                }
    }
            
            
            
            
                functionToUploadToServer(multiformData){  
                    
                      Dio dio = Dio();
                
                      final response = await dio.post(
                        url,
                        data: multiformData,
                        options: Options(
                            contentType: 'multipart/form-data',
                            headers: {},
                            followRedirects: false,
                            validateStatus: (status) {
                              return status! <= 500;
                            }),
                      );
                      print(response.statusCode);
                     
                }


 

This _upload() function require a list of picked images, api url with headers and then it will upload the image list to the server.

void _upload(List<XFile> files) async {
 for (var file in files) {
  String fname = filename;
  FormData data = FormData.fromMap({
   "file": await MultipartFile.fromFile(
     file.path,
     filename: fname,
    ),
  });

  Dio dio = new Dio();
 
  print('Image File Name: $fname');
  var response = await dio.put(url,
    data: data,
    options: Options(
      headers: {},
    ),
  );

  print(response.statusCode);
  print(response.data);
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM