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评论87阅读模式
英文:

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

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({
      &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(&#39;File Uploaded!&#39;)),
      );
    } catch (e) {
      print(&quot;exception caught: $e&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(&#39;localhost&#39;,&#39;database-username&#39;,&#39;database-password&#39;,&#39;database&#39;);
        if(!$db){
            echo &quot;Database connection failed!&quot;;
        }

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

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

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

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

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

        ?&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);
并尝试将上传的文件移到上一级文件夹。

所以尝试更改

$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;

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:

确定