我在将多个文件上传到磁盘时遇到问题。这是我的代码。
我有2张图片的请求被发送到上传功能。这2张图片位于一个名为$multiUpload
$folderPath = '/var/www/';
if (is_array($multiUpload)){
$file = array();
$filename = array();
foreach($multiUpload as $key=>$val){
// get the file extension
$file[] = explode('.',$val);
// create custom file name
$filename[] = time().'.'.$file[$key][1];
//send to the upload function
$this->uploadToDisk($folderPath, $filename[$key]);
// sleep 1 sec so that the pic names will be different
sleep(1);
}
return $filename;
}
public function uploadToDisk($folderPath, $filename)
{
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->setDestination($folderPath);
$adapter->addFilter( 'Rename',array(
'target' => $folderPath."/".$filename,
'overwrite' => true
) );
if ($adapter->receive()) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}
这将返回
Array
(
[0] => Array
(
[0] => 1332977938.jpg
[1] => 1332977939.jpg
)
)
但只有array[0][0] or 1332977938.jpg
实际上会保存到磁盘。
为什么他们现在都得救了?有线
任何想法?
答案 0 :(得分:3)
我怀疑对uploadToDisk
的第二次调用正在返回fail
,因为您只能为每个文件调用Zend_File_Transfer_Adapter_Http::receive()
一次。由于您在调用receive
时没有指定文件,因此它会在您第一次调用uploadToDisk
时收到所有文件,然后失败并显示File Upload Attack
错误。
以下是您可以尝试的一些代码。这会尝试单独接收每个文件,然后在每次调用uploadToDisk
时一次保存一个文件。
关于代码的一些注释:
uploadToDisk
($ val)的第一个参数,因为我不确定原始值是什么。它应该对应于用于文件上载的元素名称之一(请参阅Zend_File_Transfer_Adapter_Http::getFileInfo()
)以获取文件列表。sleep(1)
Zend_File_Transfer_Adapter_Abstract::setDestination()
已被弃用,将来会消失。相反,只需使用Rename
过滤器即可。使用Rename
时,setDestination()
无效。这就是......
<?php
$folderPath = '/var/www/';
if (is_array($multiUpload)){
$filenames = array();
foreach($multiUpload as $key => $val){
// get the file extension
$ext = explode('.', $val);
$ext = $ext[sizeof($ext) - 1];
// create custom file name
do {
$filename = uniqid(time()) . '.' . $ext;
$diskPath = $folderPath . $filename;
} while (file_exists($diskPath));
$filenames[$key] = $filename;
//send to the upload function
// $val is the file to receive, $diskPath is where it will be moved to
$this->uploadToDisk($val, $diskPath);
}
return $filename;
}
public function uploadToDisk($file, $filename)
{
// create the transfer adapter
// note that setDestination is deprecated, instead use the Rename filter
$adapter = new Zend_File_Transfer_Adapter_Http();
$adapter->addFilter('Rename', array(
'target' => $filename,
'overwrite' => true
));
// try to receive one file
if ($adapter->receive($file)) {
$message = "success";
} else {
$message = "fail";
}
return $message;
}