I am trying to send files to server with flutter but it return this error:
Unhandled Exception: type 'List<File>' is not a subtype of type 'String' in type cast
Code
I've commented code below for better understanding
late List<File> newDoc = [];
// Select files
ElevatedButton(
onPressed: () async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
allowMultiple: true
type: FileType.custom,
allowedExtensions: ['jpg', 'pdf', 'doc', 'docx', 'ppt', 'pptx'],
);
if(result != null) {
// Not sure if I should only get file path or complete data (this was in package documentation)
List<File> files = result.paths.map((path) => File(path!)).toList();
newDoc = files;
} else {
// User canceled the picker
}
},
child: Text('Select Files'),
),
SizedBox(height: 15.0),
// Send files to server
ElevatedButton(
onPressed: () async {
//save
var response = await http.post(
Uri.parse('https://example.come/upload/${args.id}'),
body: {
'documents': newDoc, // send array of my selected files to server
},
headers: {
HttpHeaders.authorizationHeader: '$userToken',
HttpHeaders.acceptHeader: 'application/json'
},
);
print('request::: $response');
// if (response.statusCode == 200) {
// .....
// } else {
// .....
// }
//save
},
child: Text('Save'),
),
Any suggestions?
Update
I've changed my http request to code below but my server receives empty body (the request does not send my files to backend)
var request = http.MultipartRequest('POST', uri);
request.headers['authorization'] = '$userToken';
request.headers['acceptHeader'] = 'application/json';
newDoc.map((k) async {
request.files.add(await http.MultipartFile.fromPath(
'documents', k.path
));
});
var response = await request.send();
var response2 = await http.Response.fromStream(response);
print('request::: ${response2.statusCode}');
print('request::: ${response2.body}'); // return as []