所以我已经找到了如何迭代上传到我的API的文件,该API是用Laravel 5.1构建的-在Laravel 51(作为API)中处理多个文件
现在我已经完成了,在迭代文件时,我仍然无法使用Symfony访问文件的属性。
HTML页面(用于测试):
<!DOCTYPE>
<html>
<body>
<form method="post" enctype="multipart/form-data" action="http://example.dev/files">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload">
</form>
</body>
</html>
控制器:
public function files(Request $request)
{
foreach($request->files as $file)
{
return var_dump($file->getClientOriginalName());
}
}
错误:Call to a member function getClientOriginalName() on array
如果我只是用这个控制器方法var_dump
文件:
public function files(Request $request)
{
foreach($request->files as $file)
{
return var_dump($file);
}
}
返回:
array (size=3)
0 =>
object(Symfony'Component'HttpFoundation'File'UploadedFile)[84]
private 'test' => boolean false
private 'originalName' => string 'Screen Shot 2015-10-23 at 10.07.23 AM.png' (length=41)
private 'mimeType' => string 'image/png' (length=9)
private 'size' => int 270504
private 'error' => int 0
private 'pathName' (SplFileInfo) => string '/tmp/phpzekUeL' (length=14)
private 'fileName' (SplFileInfo) => string 'phpzekUeL' (length=9)
1 =>
object(Symfony'Component'HttpFoundation'File'UploadedFile)[85]
private 'test' => boolean false
private 'originalName' => string 'Screen Shot 2015-10-26 at 7.28.59 PM.png' (length=40)
private 'mimeType' => string 'image/png' (length=9)
private 'size' => int 13687
private 'error' => int 0
private 'pathName' (SplFileInfo) => string '/tmp/phprYW7MZ' (length=14)
private 'fileName' (SplFileInfo) => string 'phprYW7MZ' (length=9)
2 =>
object(Symfony'Component'HttpFoundation'File'UploadedFile)[86]
private 'test' => boolean false
private 'originalName' => string 'Screen Shot 2015-10-27 at 2.50.58 PM.png' (length=40)
private 'mimeType' => string 'image/png' (length=9)
private 'size' => int 786350
private 'error' => int 0
private 'pathName' (SplFileInfo) => string '/tmp/phpLq3lle' (length=14)
private 'fileName' (SplFileInfo) => string 'phpLq3lle' (length=9)
为什么我要返回此Symfony错误?如何使用getClientOriginalName()
和中列出的其他函数访问foreach
循环中的文件属性http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/File/UploadedFile.html?
提前感谢您的帮助!
使用
<input type="file" name="files[]" multiple>
您要求浏览器将files
字段作为数组发送,因此最终会得到一个数组,其中包含一个文件数组。你可以做两件事之一:
1-使用这个替代:
<input type="file" name="files" multiple>
2-或者像这样更改代码:
public function files(Request $request) {
foreach($request->files as $files) {
foreach($files as $file) {
return var_dump($file->getClientOriginalName());
}
}
}
因此,我最终能够通过使用文件名称属性的count
来形成for
循环,从而进入$request->files
对象中的$_FILES['files']
数组(记住,其键是属性,而不是文件本身),从而逐步返回数组的键:
public function files(Request $request)
{
$count = count($_FILES['files']['name']);
for($i = 0; $i < $count; $i++)
{
foreach($request->files as $file)
{
echo 'The name is '.$file[$i]->getClientOriginalName().'<br>';
}
}
}
这不是最有效的方法(由于时间复杂性),但是,嘿,上传是这里的瓶颈!
希望能帮助到别人。。。