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

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\&lt;String\&gt; getFile() async {
FilePickerResult? file = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: \[\&#39;pdf\&#39;, \&#39;docx\&#39;, \&#39;jpeg\&#39;\],
);


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


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


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

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



`} else {
print(&quot;No file selected.&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;#39;localhost&amp;#39;,&amp;#39;database-username&amp;#39;,&amp;#39;database-password&amp;#39;,&amp;#39;database&amp;#39;);
        if(!$db){
            echo &amp;quot;Database connection failed!&amp;quot;;
        }

        if (!file_exists(&amp;#39;uploaddata&amp;#39;)) {
            mkdir(&amp;#39;uploaddata&amp;#39;, 0777, true); // Create folder with full permissions recursively
        }

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

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

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

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

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

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