我有一个颤振应用程序,它通过 REST api 与服务器交互,它可以获取和显示信息。它还可以向服务器发送文本信息。我想添加将 pdf 文件和图像发送到服务器的功能,但我不知道如何实现。这是选择文件的代码
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Another Attempt'),
centerTitle: true,
),
body: Container(
alignment: Alignment.topCenter,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
MaterialButton(
onPressed: () async {
FilePickerResult result =
await FilePicker.platform.pickFiles(allowMultiple: true);
if (result != null) {
List<File> files =
result.paths.map((path) => File(path)).toList();
} else {
// User canceled the picker
}
},
child: Text('Upload multiple files'),
color: Colors.blueAccent,
),
SizedBox(height: 10.0),
MaterialButton(
onPressed: () async {
FilePickerResult result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path);
} else {
// User canceled the picker
}
},
child: Text('Upload single file'),
color: Colors.blueAccent,
),
SizedBox(height: 10.0),
MaterialButton(
onPressed: () {
_submitData();
},
child: Text('Upload single file'),
color: Colors.blueAccent,
),
],
),
),
);
}
void _submitData() async {
setState(() {});
var data = {
'image': file,
'pdf': files,
};
try {
var res = await Network().postData(data, '/convert-customer');
var body = json.decode(res.body);
if (res.statusCode == 200 || res.statusCode == 201) {
print(res.statusCode);
print(body);
} else {}
} on TimeoutException catch (_) {
print("Your connection has timedout");
_formKey.currentState.reset();
} on SocketException catch (_) {
print("You are not connected to internet");
_formKey.currentState.reset();
}
setState(() {
_isLoading = false;
});
}
这是向服务器发送数据的代码
final String _baseUrl = 'http://106.20.34.127/trial/api/v1';
var token;
_getToken() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
token = jsonDecode(localStorage.getString('token'))['token'];
}
postData(data, apiUrl) async {
try {
var _finalUrl = _baseUrl + apiUrl;
Uri fullUrl = Uri.parse(_finalUrl);
await _getToken();
print(fullUrl);
return await http.post(fullUrl,
body: jsonEncode(data), headers: _setHeaders());
} catch (e) {
print(e);
}
}
我该怎么做。