This is how I picked a file from device
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: [
'jpg',
'pdf',
'doc'
],
);
List<File> files = result!.paths
.map((path) => File(path!))
.toList();
context
.read<Dropper>()
.fileCheck(result: result);
myfile = files[0];
},
Then I Converted to Uint8List :
Uint8List imgbytes = await myFile.readAsBytes();
Now I am sending that file to Php database
final url = "http://10.0.2.2:8000/api/addSurvey";
final uri = Uri.parse(url);
final response = await api.post(uri, headers: {
'Authorization': token,
}, body: {
"bill_image": imgbytes
}
It throws error msg like this : type 'Uint8List' is not a subtype of type 'String' in type cast
CodePudding user response:
var url = "http://10.0.2.2:8000/api/addSurvey";
Map<String, String> headers = {"Content-Type": "application/json",
'Authorization': token,};
var request = http.MultipartRequest("POST", Uri.parse(url));
if(_image != null){
var pic = await http.MultipartFile.fromBytes('bill_image', imgbytes , filename: 'photo.jpg');
request.files.add(pic);
}
request.send().then((result) async {
http.Response.fromStream(result).then((response) async {
if (response.statusCode == 200)
{
}
else{
}
return response.body;
});
}).catchError((err) => print('merror : ' err.toString())).whenComplete(()
{
});
Try it using multipart request.
CodePudding user response:
if php is accepting parameter as file type File then you need to send image as multipart request i guess.
var headers = {
'Authorization': 'token'
};
var request = http.MultipartRequest('POST', Uri.parse('http://10.0.2.2:8000/api/addSurvey'));
request.files.add(await http.MultipartFile.fromPath('bill_image', 'path to your file'));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}