I want to upload a file to server when users change there profile
I am using FilePicker
to pic file and base64Encode
to get the file Data
File? _tempfile;
String? _fileData;
String? _fileExe;
getFile() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.image,
allowMultiple: false,
);
if (result != null) {
setState(() {
_tempfile = File(result.files.single.path.toString());
_fileExe=result.files.single.path.toString().split(".").last;
_fileData = base64Encode(_tempfile!.readAsBytesSync());
uploadFile();
print("file is");
print(_tempfile);
print("file ext is");
print(_fileExe);
print('file data is');
print(_fileData);
});
} else {
// User canceled the picker
}
}
uploadFile() async {
print("uploding");
var userId =
await SessionManager().get('user').then((value) => value['user_id']);
try {
var response = await http.post(Uri.parse(apiCon.apiEndUserProfile),
body: {'file': _fileData, 'id': userId,'ext':_fileExe});
if (response.statusCode == 200) {
var jsonData = json.decode(response.body);
if (jsonData['status'] == "error") {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
jsonData['message'],
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.red,
));
}
else if(jsonData['status'] == "success" ){
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
jsonData['message'],
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.green,
));
setState(() {
count++;
});
}
else{
print('jsonData');
print(jsonData);
}
}
} catch (e) {
print(e);
}
}
and the php code
I use base64_encode
to get the file
if (isset($_POST['file'])&&isset($_POST['id'])&&isset($_POST['ext'])) {
$file = $_POST['file'];
$id = $_POST['id'];
$ext = $_POST['ext'];
$temp=time();
$path="file/profile/$temp$id.$ext";
$sql="UPDATE `end_user` SET `image`='$path' WHERE `end_user_id`=$id";
file_put_contents($path,base64_encode($file));
try {
$result = mysqli_query($conn, $sql);
$response['status'] = 'success';
$response['message'] ='profile update success fully';
} catch (Exception $e) {
$response['status'] = 'error';
$response['message'] = $e->getMessage();
}
} else {
$response['status'] = 'error';
$response['message'] = 'no file found';
}
echo json_encode($response);
It will add the data to server and to the data base but the database link is not correct and the file will not open
mysql data end_user
table image url
enter image description here
server files enter image description here
when I try to open the file it will be like https://psychologycounseling.000webhostapp.com/file/profile/1682792061163.jpeg
When you already receiving base64 encoded image from app side, you have to decode it first before saving into file.
Replace
file_put_contents($path,base64_encode($file));
with
file_put_contents($path,base64_decode($file));