[英]Multiple upload files in Symfony2
I try to upload multiple files in Symfony2. 我尝试在Symfony2中上传多个文件。 I need do this without handling in controller, and i try do that trought lifecycles, but i cant create multiple instances of my entity, i think i need modify , method:
我需要在控制器中不进行处理的情况下执行此操作,而我尝试这样做要经历生命周期,但是我无法创建实体的多个实例,我认为我需要进行修改,方法:
/**
* Sets file.
*
* @param UploadedFile $photo
*/
public function setPhoto(UploadedFile $photo = null)
{
$this->photo = $photo;
if (isset($this->path)) {
$this->temp = $this->path;
$this->path = null;
} else {
$this->path = 'initial';
}
}
To something like that: 对于这样的事情:
/**
* Sets file.
*
* @param ArrayCollection $photo
*/
public function setPhoto(ArrayCollection $photo = null)
{
foreach ($photo as $photos) {
$file = new UploadedFile();
$this->photo = $file;
}
}
I am newbie help please. 我是新手,请帮忙。
Multiple file upload is tricky with Symfony2. 使用Symfony2上载多个文件非常棘手。 I use PHP uploads along with Doctrine to upload multiple files with this :
我将PHP上载与Doctrine一起使用来上载多个文件:
if(isset($_FILES['files']))
{
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name )
{
$file_name = $_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 6097152) //whatever size you want
{
$errors[]='File size must be less than 6 MB';
}
$entity = new Entity; //your file entity
//Do whatever you want with the entity...
$request = $this->get('request');
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$desired_dir=__DIR__.'/../../../../web/[Your desired folder]/'.$entity->getId()."/";
if(empty($errors)==true)
{
if(is_dir($desired_dir)==false)
{
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false)
{
move_uploaded_file($file_tmp,__DIR__.'/../../../../web/[Your desired folder]/'.$entity->getId()."/".$file_name);
}
else
{ //rename the file if another one exist
$new_dir=__DIR__.'/../../../../web/Flightpics/'.$flight->getId()."/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
}
else
{
//print errors if needed
}
}
if(empty($error)){
//print success if needed
}
}
All files will be processed into your web/[your folder]/[your entity id] folder. 所有文件将被处理到您的web / [您的文件夹] / [您的实体ID]文件夹中。 In your HTML code, your form should look like this:
在HTML代码中,表单应如下所示:
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/ required>
<hr>
<input type="submit"/ value="Ajouter" class="btn btn-success">
</form>
Do not forget the name="files[]" part to get an array of files. 不要忘了name =“ files []”部分来获取文件数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.