gpt4 book ai didi

php - 在 Laravel 中 Dio 为空的 Flutter 文件上传

转载 作者:IT王子 更新时间:2023-10-29 07:21:20 26 4
gpt4 key购买 nike

我无法使用 Dio 插件上传文件,我不知道问题出在哪里。在 Laravel 中,请求总是空的。

到目前为止我做了什么:

  1. 使用 existsSync() 函数仔细检查文件路径是否确实存在
  2. Content-Type 更改为 application/x-www-form-urlencoded
  3. 验证文件是否正在上传 - 似乎是(?)

这是我的 flutter 代码:

File myFile = new File('/storage/emulated/0/Download/demo.docx');

FormData form = new FormData.from({
'title': 'Just testing',
'file': new UploadFileInfo(myFile, 'demo.docx')
});

在通过 POST 发送之前,我检查了文件是否存在并返回 true

print(myFile.existsSync());

并正确设置Content-type

Response response = await Dio().post(
myUrl,
data: form,
options: new Options(
contentType: ContentType.parse("application/x-www-form-urlencoded"),
),
);

打印表单返回的结果

I/flutter (27929): ----dio-boundary-0118165894
I/flutter (27929): Content-Disposition: form-data; name="title"

I/flutter (27929): ----dio-boundary-1759467036
I/flutter (27929): Content-Disposition: form-data; name="file"; filename="demo.docx"
I/flutter (27929): Content-Type: application/octet-stream

我认为这表明文件正在上传。

现在在 laravel 中,每当我输出接收到的内容时,它总是将键 file 变为 null,但是键 title 带有数据。

代码print_r(json_encode($request->all()))获取

{"title":"Just testing","file":{}}

print_r(json_encode($request->file('file'))) 也是如此。

我错过了什么?

最佳答案

已解决。

这花了我一段时间才弄明白,但我最终意识到这种方法有两个问题:

  1. Laravel $request是空的,但是 $_FILES不是
  2. 发送多个文件不能使用数组作为documentation发送告诉

所以,为了实现我允许用户动态选择多个文件并同时上传的目标,这是背后的逻辑:

flutter

必须在不立即设置文件的情况下创建表单:

FormData form = new FormData.from(
{
'title': 'Just testing',
});

自函数.fromMap<String, dynamic>后面可以加值。

/* 
* files = List<String> containing all the file paths
*
* It will end up like this:
* file_1 => $_FILES
* file_2 => $_FILES
* file_3 => $_FILES
*/
for (int i = 0; i < files.length; i++) {
form.add('file_' + i.toString(),
new UploadFileInfo(new File(files[i]), files[i].toString()));
}

无需设置不同的Content-Type ,因此这就足够了:

Response response = await Dio().post(myUrl, data: form);

拉拉维尔/PHP

忘记访问 file通过$request->file()而是使用老派的方法。

$totalFiles = count($_FILES);

for ($i = 0; $i < $totalFiles; $i++)
{
$file = $_FILES['file_' . $i];

// handle the file normally ...
$fileName = basename($file['name']);
$fileInfo = pathinfo($file);
$fileExtension = $fileInfo['extension'];

move_uploaded_file($file['tmp_name'], $path);
}

关于php - 在 Laravel 中 Dio 为空的 Flutter 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55478345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com