Unable to save/upload files to a folder on server with Dio and File_picker flutter packages & I am doing this with PHP

huangapple go评论150阅读模式
英文:

Unable to save/upload files to a folder on server with Dio and File_picker flutter packages & I am doing this with PHP

问题

我面临的问题是我上传到服务器的文件没有被上传到文件夹中,而是文件名被提交到数据库中。我提供了与选择文件并将其上传到服务器相关的所有数据。

我的Flutter代码是:

  1. Dio dio = Dio(); // 初始化Dio实例
  2. String? filePath;
  3. Future<String> getFile() async {
  4. FilePickerResult? file = await FilePicker.platform.pickFiles(
  5. type: FileType.custom,
  6. allowedExtensions: ['pdf', 'docx', 'jpeg'],
  7. );
  8. if (file != null && file.files.isNotEmpty) {
  9. List<String> paths = file.files.map((file) => file.path!).toList();
  10. print("Selected file paths: $paths");
  11. return paths[0]; // 返回第一个选定的文件路径
  12. }
  13. return ''; // 如果未选择文件,则返回空字符串
  14. }
  15. Future<void> _uploadFile(String filePath) async {
  16. if (filePath.isNotEmpty) {
  17. String originalFileName = basename(filePath);
  18. String randomFileName =
  19. '${DateTime.now().millisecondsSinceEpoch}_$originalFileName';
  20. FormData formData = FormData.fromMap({
  21. "file":
  22. await MultipartFile.fromFile(filePath, filename: randomFileName),
  23. });
  24. try {
  25. Response response = await dio.post(
  26. "path-to-my-file-uploading-php-code",
  27. data: formData,
  28. );
  29. print("file upload response status code: ${response.statusCode}");
  30. print("file upload response data: ${response.data}");
  31. ScaffoldMessenger.of(context).showSnackBar(
  32. const SnackBar(content: Text('File Uploaded!')),
  33. );
  34. } catch (e) {
  35. print("exception caught: $e");
  36. }
  37. } else {
  38. print("No file selected.");
  39. }
  40. }

这是用于选择和提交文件的UI:

  1. Center(
  2. child: ElevatedButton(
  3. onPressed: () async {
  4. String filePath =
  5. await getFile(); // 获取所选文件的路径
  6. if (filePath.isNotEmpty) {
  7. _uploadFile(
  8. filePath); // 使用文件路径调用_uploadFile函数
  9. } else {
  10. print("No file selected.");
  11. }
  12. },
  13. child: Text('提交表单'),
  14. style: ElevatedButton.styleFrom(
  15. minimumSize: Size(150, 50),
  16. primary: Color(0xffcc493f),
  17. shape: RoundedRectangleBorder(
  18. borderRadius: BorderRadius.zero)),
  19. ),
  20. ),

这是我的用于上传文件到文件夹的PHP代码:

  1. <?php
  2. $db = mysqli_connect('localhost','database-username','database-password','database');
  3. if(!$db){
  4. echo "数据库连接失败!";
  5. }
  6. if (!file_exists('uploaddata')) {
  7. mkdir('uploaddata', 0777, true); // 递归创建带有完全权限的文件夹
  8. }
  9. $files = $_FILES['file']['name'];
  10. $file_path = '../uploaddata/'.$files;
  11. $temp_name = $_FILES['file']['temp_name'];
  12. if (move_uploaded_file($temp_name, $file_path)) {
  13. // 文件成功移动,继续进行数据库插入
  14. $db->query("INSERT INTO filesupload(files) VALUES('".$files."')");
  15. } else {
  16. echo "文件上传失败。";
  17. }
  18. echo "文件路径:" . $file_path;
  19. $db->query("INSERT INTO filesupload(files)VALUES('".$files."')");
  20. ?>

附件文件显示了我在Debug控制台中收到的错误:

Unable to save/upload files to a folder on server with Dio and File_picker flutter packages & I am doing this with PHP

英文:

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:

  1. Dio dio = Dio(); // Initialize Dio instance
  2. String? filePath;
  3. Future&lt;String&gt; getFile() async {
  4. FilePickerResult? file = await FilePicker.platform.pickFiles(
  5. type: FileType.custom,
  6. allowedExtensions: [&#39;pdf&#39;, &#39;docx&#39;, &#39;jpeg&#39;],
  7. );
  8. if (file != null &amp;&amp; file.files.isNotEmpty) {
  9. List&lt;String&gt; paths = file.files.map((file) =&gt; file.path!).toList();
  10. print(&quot;Selected file paths: $paths&quot;);
  11. return paths[0]; // Return the first selected file path
  12. }
  13. return &#39;&#39;; // Return an empty string if no file is selected
  14. }
  15. Future&lt;void&gt; _uploadFile(String filePath) async {
  16. if (filePath.isNotEmpty) {
  17. String originalFileName = basename(filePath);
  18. String randomFileName =
  19. &#39;${DateTime.now().millisecondsSinceEpoch}_$originalFileName&#39;;
  20. FormData formData = FormData.fromMap({
  21. &quot;file&quot;:
  22. await MultipartFile.fromFile(filePath, filename: randomFileName),
  23. });
  24. try {
  25. Response response = await dio.post(
  26. &quot;path-to-my-file-uploading-php-code&quot;,
  27. data: formData,
  28. );
  29. print(&quot;file upload response status code: ${response.statusCode}&quot;);
  30. print(&quot;file upload response data: ${response.data}&quot;);
  31. ScaffoldMessenger.of(context).showSnackBar(
  32. const SnackBar(content: Text(&#39;File Uploaded!&#39;)),
  33. );
  34. } catch (e) {
  35. print(&quot;exception caught: $e&quot;);
  36. }
  37. } else {
  38. print(&quot;No file selected.&quot;);
  39. }
  40. }

This is the UI for selecting and submitting file:

  1. Center(
  2. child: ElevatedButton(
  3. onPressed: () async {
  4. String filePath =
  5. await getFile(); // Get the selected file path
  6. if (filePath.isNotEmpty) {
  7. _uploadFile(
  8. filePath); // Call the _uploadFile function with the file path
  9. } else {
  10. print(&quot;No file selected.&quot;);
  11. }
  12. },
  13. child: Text(&#39;SUBMIT FORM&#39;),
  14. style: ElevatedButton.styleFrom(
  15. minimumSize: Size(150, 50),
  16. primary: Color(0xffcc493f),
  17. shape: RoundedRectangleBorder(
  18. borderRadius: BorderRadius.zero)),
  19. ),
  20. ),

This is my PHP code for uploading file to the folder:

  1. &lt;?php
  2. $db = mysqli_connect(&#39;localhost&#39;,&#39;database-username&#39;,&#39;database-password&#39;,&#39;database&#39;);
  3. if(!$db){
  4. echo &quot;Database connection failed!&quot;;
  5. }
  6. if (!file_exists(&#39;uploaddata&#39;)) {
  7. mkdir(&#39;uploaddata&#39;, 0777, true); // Create folder with full permissions recursively
  8. }
  9. $files = $_FILES[&#39;file&#39;][&#39;name&#39;];
  10. $file_path = &#39;../uploaddata/&#39;.$files;
  11. $temp_name = $_FILES[&#39;file&#39;][&#39;temp_name&#39;];
  12. if (move_uploaded_file($temp_name, $file_path)) {
  13. // File moved successfully, proceed with database insertion
  14. $db-&gt;query(&quot;INSERT INTO filesupload(files) VALUES(&#39;&quot;.$files.&quot;&#39;)&quot;);
  15. } else {
  16. echo &quot;File upload failed.&quot;;
  17. }
  18. echo &quot;File path: &quot; . $file_path;
  19. $db-&gt;query(&quot;INSERT INTO filesupload(files)VALUES(&#39;&quot;.$files.&quot;&#39;)&quot;);
  20. ?&gt;

The attachment file indicating the error I am receiving in Debug Console:

Unable to save/upload files to a folder on server with Dio and File_picker flutter packages & I am doing this with PHP

答案1

得分: 1

在当前路径上创建文件夹 mkdir('uploaddata', 0777, true);
并尝试将上传的文件移到上一级文件夹。

所以尝试更改

  1. $file_path = '../uploaddata/'.$files;

  1. $file_path = './uploaddata/'.$files;
英文:

You creating folder on current path mkdir(&#39;uploaddata&#39;, 0777, true);
and trying move uploaded file to one folder up.

So try change

  1. $file_path = &#39;../uploaddata/&#39;.$files;

to

  1. $file_path = &#39;./uploaddata/&#39;.$files;

huangapple
  • 本文由 发表于 2023年8月10日 17:31:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76874426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定