我正在尝试使用颤振将文件发送到服务器,但它返回此错误:
Unhandled Exception: type 'List<File>' is not a subtype of type 'String' in type cast
代码
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'),
),
有什么建议么?
更新
我已将我的 http 请求更改为下面的代码,但我的服务器收到空正文(请求不会将我的文件发送到后端)
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 []