51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

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

英文:

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

问题 {#heading}

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

我的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({
  &quot;file&quot;:
      await MultipartFile.fromFile(filePath, filename: randomFileName),
});

try { Response response = await dio.post( &quot;path-to-my-file-uploading-php-code&quot;, data: formData, ); print(&quot;file upload response status code: ${response.statusCode}&quot;); print(&quot;file upload response data: ${response.data}&quot;); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('File Uploaded!')), ); } catch (e) { print(&quot;exception caught: $e&quot;); }

} 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控制台中收到的错误:

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:

Dio dio = Dio(); // Initialize Dio instance
String? filePath;

Future&amp;lt;String&amp;gt; getFile() async { FilePickerResult? file = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: [&amp;#39;pdf&amp;#39;, &amp;#39;docx&amp;#39;, &amp;#39;jpeg&amp;#39;], );

if (file != null &amp;amp;&amp;amp; file.files.isNotEmpty) { List&amp;lt;String&amp;gt; paths = file.files.map((file) =&amp;gt; file.path!).toList(); print(&amp;quot;Selected file paths: $paths&amp;quot;); return paths[0]; // Return the first selected file path } return &amp;#39;&amp;#39;; // Return an empty string if no file is selected }

Future&amp;lt;void&amp;gt; uploadFile(String filePath) async { if (filePath.isNotEmpty) { String originalFileName = basename(filePath); String randomFileName = &amp;#39;${DateTime.now().millisecondsSinceEpoch}$originalFileName&amp;#39;;

FormData formData = FormData.fromMap({
  &amp;amp;quot;file&amp;amp;quot;:
      await MultipartFile.fromFile(filePath, filename: randomFileName),
});

try { Response response = await dio.post( &amp;amp;quot;path-to-my-file-uploading-php-code&amp;amp;quot;, data: formData, ); print(&amp;amp;quot;file upload response status code: ${response.statusCode}&amp;amp;quot;); print(&amp;amp;quot;file upload response data: ${response.data}&amp;amp;quot;); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text(&amp;amp;#39;File Uploaded!&amp;amp;#39;)), ); } catch (e) { print(&amp;amp;quot;exception caught: $e&amp;amp;quot;); }

} else { print(&amp;quot;No file selected.&amp;quot;); } }


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(&quot;No file selected.&quot;);
      }
    },
    child: Text(&#39;SUBMIT FORM&#39;),
    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:

        &lt;?php 
    $db = mysqli_connect(&amp;amp;#39;localhost&amp;amp;#39;,&amp;amp;#39;database-username&amp;amp;#39;,&amp;amp;#39;database-password&amp;amp;#39;,&amp;amp;#39;database&amp;amp;#39;);
    if(!$db){
        echo &amp;amp;quot;Database connection failed!&amp;amp;quot;;
    }
if (!file_exists(&amp;amp;amp;#39;uploaddata&amp;amp;amp;#39;)) {
    mkdir(&amp;amp;amp;#39;uploaddata&amp;amp;amp;#39;, 0777, true); // Create folder with full permissions recursively
}

$files = $_FILES[&amp;amp;amp;#39;file&amp;amp;amp;#39;][&amp;amp;amp;#39;name&amp;amp;amp;#39;];

$file_path = &amp;amp;amp;#39;../uploaddata/&amp;amp;amp;#39;.$files;
$temp_name = $_FILES[&amp;amp;amp;#39;file&amp;amp;amp;#39;][&amp;amp;amp;#39;temp_name&amp;amp;amp;#39;];

if (move_uploaded_file($temp_name, $file_path)) {
    // File moved successfully, proceed with database insertion
    $db-&amp;amp;amp;gt;query(&amp;amp;amp;quot;INSERT INTO filesupload(files) VALUES(&amp;amp;amp;#39;&amp;amp;amp;quot;.$files.&amp;amp;amp;quot;&amp;amp;amp;#39;)&amp;amp;amp;quot;);
} else {
    echo &amp;amp;amp;quot;File upload failed.&amp;amp;amp;quot;;
}
echo &amp;amp;amp;quot;File path: &amp;amp;amp;quot; . $file_path;

$db-&amp;amp;amp;gt;query(&amp;amp;amp;quot;INSERT INTO filesupload(files)VALUES(&amp;amp;amp;#39;&amp;amp;amp;quot;.$files.&amp;amp;amp;quot;&amp;amp;amp;#39;)&amp;amp;amp;quot;);

?&amp;amp;amp;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}

得分: 1

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

所以尝试更改

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

$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

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

to

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

赞(3)
未经允许不得转载:工具盒子 » Unable to save/upload files to a folder on server with Dio and File_picker flutter packages & I am doing this with PHP