英文:
Unable to save/upload files to a folder on server with Dio and File_picker flutter packages & I am doing this with PHP
问题
我面临的问题是我上传到服务器的文件没有被上传到文件夹中,而是文件名被提交到数据库中。我提供了与选择文件并将其上传到服务器相关的所有数据。
我的Flutter代码是:
Dio dio = Dio(); // 初始化Dio实例
String? filePath;
Future<String> getFile() async {
FilePickerResult? file = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf', 'docx', 'jpeg'],
);
if (file != null && file.files.isNotEmpty) {
List<String> paths = file.files.map((file) => file.path!).toList();
print("Selected file paths: $paths");
return paths[0]; // 返回第一个选定的文件路径
}
return ''; // 如果未选择文件,则返回空字符串
}
Future<void> _uploadFile(String filePath) async {
if (filePath.isNotEmpty) {
String originalFileName = basename(filePath);
String randomFileName =
'${DateTime.now().millisecondsSinceEpoch}_$originalFileName';
FormData formData = FormData.fromMap({
"file":
await MultipartFile.fromFile(filePath, filename: randomFileName),
});
try {
Response response = await dio.post(
"path-to-my-file-uploading-php-code",
data: formData,
);
print("file upload response status code: ${response.statusCode}");
print("file upload response data: ${response.data}");
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('File Uploaded!')),
);
} catch (e) {
print("exception caught: $e");
}
} else {
print("No file selected.");
}
}
这是用于选择和提交文件的UI:
Center(
child: ElevatedButton(
onPressed: () async {
String filePath =
await getFile(); // 获取所选文件的路径
if (filePath.isNotEmpty) {
_uploadFile(
filePath); // 使用文件路径调用_uploadFile函数
} else {
print("No file selected.");
}
},
child: Text('提交表单'),
style: ElevatedButton.styleFrom(
minimumSize: Size(150, 50),
primary: Color(0xffcc493f),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.zero)),
),
),
这是我的用于上传文件到文件夹的PHP代码:
<?php
$db = mysqli_connect('localhost','database-username','database-password','database');
if(!$db){
echo "数据库连接失败!";
}
if (!file_exists('uploaddata')) {
mkdir('uploaddata', 0777, true); // 递归创建带有完全权限的文件夹
}
$files = $_FILES['file']['name'];
$file_path = '../uploaddata/'.$files;
$temp_name = $_FILES['file']['temp_name'];
if (move_uploaded_file($temp_name, $file_path)) {
// 文件成功移动,继续进行数据库插入
$db->query("INSERT INTO filesupload(files) VALUES('".$files."')");
} else {
echo "文件上传失败。";
}
echo "文件路径:" . $file_path;
$db->query("INSERT INTO filesupload(files)VALUES('".$files."')");
?>
附件文件显示了我在Debug控制台中收到的错误:
英文:
The problem I am facing is that the files I upload ta server are not being uploaded inside a folder but the filename is submitting into the database. I am providing all data related to selecting a file and then uploading it to the server
My flutter code is:
Dio dio = Dio(); // Initialize Dio instance
String? filePath;
Future<String> getFile() async {
FilePickerResult? file = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf', 'docx', 'jpeg'],
);
if (file != null && file.files.isNotEmpty) {
List<String> paths = file.files.map((file) => file.path!).toList();
print("Selected file paths: $paths");
return paths[0]; // Return the first selected file path
}
return ''; // Return an empty string if no file is selected
}
Future<void> _uploadFile(String filePath) async {
if (filePath.isNotEmpty) {
String originalFileName = basename(filePath);
String randomFileName =
'${DateTime.now().millisecondsSinceEpoch}_$originalFileName';
FormData formData = FormData.fromMap({
"file":
await MultipartFile.fromFile(filePath, filename: randomFileName),
});
try {
Response response = await dio.post(
"path-to-my-file-uploading-php-code",
data: formData,
);
print("file upload response status code: ${response.statusCode}");
print("file upload response data: ${response.data}");
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('File Uploaded!')),
);
} catch (e) {
print("exception caught: $e");
}
} else {
print("No file selected.");
}
}
This is the UI for selecting and submitting file:
Center(
child: ElevatedButton(
onPressed: () async {
String filePath =
await getFile(); // Get the selected file path
if (filePath.isNotEmpty) {
_uploadFile(
filePath); // Call the _uploadFile function with the file path
} else {
print("No file selected.");
}
},
child: Text('SUBMIT FORM'),
style: ElevatedButton.styleFrom(
minimumSize: Size(150, 50),
primary: Color(0xffcc493f),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.zero)),
),
),
This is my PHP code for uploading file to the folder:
<?php
$db = mysqli_connect('localhost','database-username','database-password','database');
if(!$db){
echo "Database connection failed!";
}
if (!file_exists('uploaddata')) {
mkdir('uploaddata', 0777, true); // Create folder with full permissions recursively
}
$files = $_FILES['file']['name'];
$file_path = '../uploaddata/'.$files;
$temp_name = $_FILES['file']['temp_name'];
if (move_uploaded_file($temp_name, $file_path)) {
// File moved successfully, proceed with database insertion
$db->query("INSERT INTO filesupload(files) VALUES('".$files."')");
} else {
echo "File upload failed.";
}
echo "File path: " . $file_path;
$db->query("INSERT INTO filesupload(files)VALUES('".$files."')");
?>
The attachment file indicating the error I am receiving in Debug Console:
答案1
得分: 1
在当前路径上创建文件夹 mkdir('uploaddata', 0777, true);
并尝试将上传的文件移到上一级文件夹。
所以尝试更改
$file_path = '../uploaddata/'.$files;
为
$file_path = './uploaddata/'.$files;
英文:
You creating folder on current path mkdir('uploaddata', 0777, true);
and trying move uploaded file to one folder up.
So try change
$file_path = '../uploaddata/'.$files;
to
$file_path = './uploaddata/'.$files;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论