我正在尝试创建一个包含文件字段的表单来上传视频和音频文件。 我可以上传音频文件,但不能上传视频。 当我上传MP3文件时,扩展名是.mpga而不是.mp3。
这是我的代码,(我自动化所有类型的文件以避免mimetypes的问题):
$product = new Bfile();
$form_upload = $this->createForm(new BfileType(), $product);
$form_upload->handleRequest($request);
if ($form_upload->isValid()) {
// $file stores the uploaded PDF file
/** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = $product->getBrochure();
// Generate a unique name for the file before saving it
$fileName = md5(uniqid()).'.'.$file->guessExtension();
// Move the file to the directory where brochures are stored
$brochuresDir = $this->container->getParameter('kernel.root_dir').'/../web/uploads';
$file->move($brochuresDir, $fileName);
// instead of its contents
$product->setBrochure($fileName);
// ... persist the $product variable or any other work
return $this->render(...);
}
我的表格:
<?php
namespace RS\VideosBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class BfileType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('brochure', 'file')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'RS\VideosBundle\Entity\Bfile'
));
}
/**
* @return string
*/
public function getName()
{
return 'rs_videosbundle_bfile';
}
}
我的实体:
<?php
namespace RS\VideosBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Bfile
*/
class Bfile
{
/**
* @var integer
*/
private $id;
/**
* @var string
* @Assert\File(maxSize ="1000M")
*/
private $brochure;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set brochure
*
* @param string $brochure
*
* @return Bfile
*/
public function setBrochure($brochure)
{
$this->brochure = $brochure;
return $this;
}
/**
* Get brochure
*
* @return string
*/
public function getBrochure()
{
return $this->brochure;
}
}
我没有错误但是我的上传文件夹中没有视频文件。
感谢。
答案 0 :(得分:5)
我想说有很多东西看起来很奇怪:
upload_max_filesize = xxM
和post_max_size = xxM
client_max_body_size 8m;
apache应该使用php.ini值。$fileName = md5(uniqid()).'.'.$file->guessExtension();
这将通过MimeType重命名扩展名的文件 - 你的文件名是什么并不重要,比如test.txt - 当它的mime类型是mpeg layer3时它会把它改成mp3。来自guesser类:
/**
* Returns the extension based on the mime type.
*
* If the mime type is unknown, returns null.
*
* This method uses the mime type as guessed by getMimeType()
* to guess the file extension.
*
* @return string|null The guessed extension or null if it cannot be guessed
*
* @api
*
* @see ExtensionGuesser
* @see getMimeType()
*/
public function guessExtension()
{
$type = $this->getMimeType();
$guesser = ExtensionGuesser::getInstance();
return $guesser->guess($type);
}