我无法使用Dio插件上传文件,也无法确定问题出在哪里。在Laravel中,请求总是空的。
到目前为止我做了什么:
使用existsSync()函数再次检查文件路径是否确实存在
Content-Type更改为application/x-www-form-urlencoded
已验证文件是否实际正在上载-似乎是(?)
这是我的颤振代码:

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());

并正确设置
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中,每当我输出接收到的内容时,它总是空键Content-type,但键form带有数据。
代码检索
{"title":"Just testing","file":{}}

file也是如此。
我错过了什么?

最佳答案

解决了的。
我花了一段时间才弄明白,但我最终意识到这种方法有两个问题:
laravel$request为空,但$_FILES不是
无法使用数组发送多个文件,如documentation所示。
因此,为了实现我的目标,允许用户动态选择多个文件并同时上载它们,下面是逻辑:
颤振
必须在不立即设置文件的情况下创建表单:

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

由于函数.from是一个Map<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/

10-11 19:23
查看更多