0

我一直在与 Symfony 合作进行一个项目,并且在上传文件时遇到问题,我只是想知道是否有人能指出我正确的方向?

这是我的控制器:

<?php

namespace File\IRBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use File\IRBundle\Entity\File;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this->render('FileIRBundle:Default:index.html.twig', array('name' => $name));
    }

public function upload()
{
    if (null === $this->getFile()) {
        return;
    }

    $this->getFile()->move(
        $this->getUploadRootDir(),
        $this->getFile()->getClientOriginalName()
    );

    $this->path = $this->getFile()->getClientOriginalName();
    $this->file = null;
}

/**
 * @Template()
 */
public function uploadAction(Request $request)
{
    $file = new File();

    $form = $this->createFormBuilder($file)
                 ->add('title', null, array(
                    'label' => 'Title'
                 ))
                 ->add('impulseResponseType', 'choice',  array(
                    'choices' => array(
                        'environment' => 'Environment',
                        'hardware'    => 'Hardware',
                        'speaker'     => 'Speaker'
                    ),
                    'label' => 'Impulse Response Type'
                 ))
                 ->add('impulseSource', 'choice', array(
                    'choices' => array(
                        'sine sweep'        => 'Sine Sweep',
                        'balloon pop'       => 'Balloon Pop',
                        'white-noise burst' => 'White-Noise Burst',
                        'start pistol'      => 'Start Pistol',
                        'hand clap'         => 'Hand Clap',
                        'other'             => 'Other'
                    ),
                    'label' => 'Impulse Source'
                 ))
                 ->add('softwareUsed', null, array(
                    'label' => 'Software Used'
                 ))
                 ->add('bitDepth', 'choice', array(
                    'choices' => array(
                        '16' => '16-Bit',
                        '24' => '24-Bit',
                        '32' => '32-Bit Float'
                    ),
                    'label' => 'Bit-Depth'
                 ))
                 ->add('sampleRate', 'choice', array(
                    'choices' => array(
                        '44100'  => '44.1kHz',
                        '48000'  => '48kHz',
                        '88200'  => '88.2kHz',
                        '96000'  => '96kHz',
                        '192000' => '192kHz'
                    ),
                    'label' => 'Sample Rate'
                 ))
                 ->add('impulseFormat', 'choice', array(
                    'choices' => array(
                        'mono'   => 'Mono',
                        'stereo' => 'Stereo'
                    ),
                    'label' => 'Impulse Format'
                 ))
                 ->add('microphoneUsed', null, array(
                    'label' => 'Microphone Used'
                 ))
                 ->add('preAmpUsed', null, array(
                    'label' => 'Pre-Amp Used'
                 ))
                 ->add('location', null, array(
                    'label' => 'Location'
                 ))
                 ->add('description', null, array(
                    'label' => 'Description'
                 ))
                 ->add('tags', null, array(
                    'label' => 'Tags (separate with comma\'s)'
                 ))
                 ->add('file', null, array(
                    'label' => 'Select File'
                 ))
                 ->getForm();

       if ($this->getRequest()->isMethod('POST')) {
            $form->bind($this->getRequest());
            if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $user = $this->get('security.context')->getToken()->getUser();
            $id = $user->getId();

            $file->setDate(new \DateTime());
            $file->setUser_id($user);

            $em->persist($file);
            $em->flush();

            return $this->redirect($this->generateUrl('site_index'));
            }

       }

    return array('form' => $form->createView());
}
}

这是我的实体:

<?php

namespace File\IRBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class File
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;
/**
 * @param $temp
 */
private $temp;

/**
 * @Assert\File(maxSize="1048576")
 * @var File\IRBundle\Entity\File $file
 */
public $file;


 /**
 * @ORM\Column(type="string", length=255)
 */
public $title;


/**
 * @ORM\Column(type="string", length=125)
 */
public $impulseResponseType;

/**
 * @ORM\Column(type="string", length=125)
 */
public $impulseSource;

/**
 * @ORM\Column(type="string", length=555, nullable=true)
 */
public $softwareUsed;

/**
 * @ORM\Column(type="string", length=3)
 */
public $bitDepth;

/**
 * @ORM\Column(type="integer", length=12)
 */
public $sampleRate;

/**
 * @ORM\Column(type="string", length=12)
 */
public $impulseFormat;

/**
 * @ORM\Column(type="string", length=125, nullable=true)
 */
public $microphoneUsed;

/**
 * @ORM\Column(type="string", length=125, nullable=true)
 */
public $preAmpUsed;

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
public $location;

/**
 * @ORM\Column(type="string", length=555, nullable=true)
 */
public $tags;

/**
 * @ORM\Column(type="text", nullable=true)
 */
public $description;

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
public $path;

 /**
 * @ORM\ManyToOne(targetEntity="Account\UserBundle\Entity\User", inversedBy="id")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */ 
public $user_id;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="date", type="datetime")
 */
public $date;

public function setId($id)
{
    $this->id = $id;

    return $this;
}

/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set title
 *
 * @param string $title
 * @return File
 */
public function setTitle($title)
{
    $this->title = $title;

    return $this;
}

/**
 * Get title
 *
 * @return string 
 */
public function getTitle()
{
    return $this->title;
}

/**
 * Set impulseResponseType
 *
 * @param string $impulseResponseType
 * @return File
 */
public function setImpulseResponseType($impulseResponseType)
{
    $this->impulseResponseType = $impulseResponseType;

    return $this;
}

/**
 * Get impulseResponseType
 *
 * @return string
 */
public function getImpulseResponseType()
{
    return $this->impulseResponseType;
}

/**
 * Set impulseSource
 *
 * @return string
 */
public function setImpulseSource($impulseSource)
{
    $this->impulseSource = $impulseSource;

    return $this;
}

/**
 * Get impulseSource
 *
 * @return  string
 */
public function getImpulseSource()
{
    return $this->impulseSource;
}

/**
 * Set softwareUsed
 */
public function setSoftwareUsed($softwareUsed)
{
    $this->softwareUsed = $softwareUsed;

    return $this;
}

/**
 * Get softwareUsed
 */
public function getSoftwareUsed()
{
    return $this->softwareUsed;
}

/**
 * Set bitDepth
 */
public function setBitDepth($bitDepth)
{
    $this->bitDepth = $bitDepth;

    return $this;
}

/**
 * Get bitDepth
 */
public function getBitDepth()
{
    return $this->bitDepth;
}

/**
 * Set sampleRate
 */
public function setSampleRate($sampleRate)
{
    $this->sampleRate = $sampleRate;

    return $this;
}

/**
 * Get sampleRate
 */
public function getSampleRate()
{
    return $this->sampleRate;
}

/**
 * Set impulseFormat
 */
public function setImpulseFormat($impulseFormat)
{
    $this->impulseFormat = $impulseFormat;

    return $this;
}

/**
 * Get impulseFormat
 */
public function getImpulseFormat()
{
    return $this->impulseFormat;
}

/**
 * Set microphoneUsed
 */
public function setMicrophoneUsed($microphoneUsed)
{
    $this->microphoneUsed = $microphoneUsed;

    return $this;
}

/**
 * Get microphoneUsed
 */
public function getMicrophoneUsed()
{
    return $this->microphoneUsed;
}

/**
 * Set preAmpUsed
 */
public function setPreAmpUsed($preAmpUsed)
{
    $this->preAmpUsed = $preAmpUsed;

    return $this;
}

/**
 * Get preAmpUsed
 */
public function getPreAmpUsed()
{
    return $this->preAmpUsed;
}

/**
 * Set tags
 *
 * @param string $tags
 * @return File
 */
public function setTags($tags)
{
    $this->tags = $tags;

    return $this;
}

/**
 * Get tag1
 *
 * @return string 
 */
public function getTags()
{
    return $this->tags;
}

/**
 * Set description
 *
 * @param string $description
 * @return File
 */
public function setDescription($description)
{
    $this->description = $description;

    return $this;
}

/**
 * Get description
 *
 * @return string 
 */
public function getDescription()
{
    return $this->description;
}

/**
 * Set location
 *
 * @param string $location
 * @return File
 */
public function setLocation($location)
{
    $this->location = $location;

    return $this;
}

/**
 * Get location
 *
 * @return string 
 */
public function getLocation()
{
    return $this->location;
}


/**
 * Set username
 *
 * @param string $user_id
 * @return File
 */
public function setUser_id($user_id)
{
    $this->user_id = $user_id;

    return $this;
}

/**
 * Get username
 *
 * @return string 
 */
public function getUser_id()
{
    return $this->user_id;
}

/**
 * Set date
 *
 * @param \DateTime $date
 * @return File
 */
public function setDate($date)
{
    $this->date = $date;

    return $this;
}

/**
 * Get date
 *
 * @return \DateTime 
 */
public function getDate()
{
    return $this->date;
}

public function getWebPath()
{
    return null === $this->path
        ? null
        : $this->getUploadDir().'/'.$this->path;
}

protected function getUploadRootDir()
{
    // the absolute directory path where uploaded
    // documents should be saved
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

protected function getUploadDir()
{
    // get rid of the __DIR__ so it doesn't screw up
    // when displaying uploaded doc/image in the view.
    return 'uploads/';
}

public function setFile(UploadedFile $file = null)
{
    $this->file = $file;
    // check if we have an old image path
    if (is_file($this->getAbsolutePath())) {
        // store the old name to delete after the update
        $this->temp = $this->getAbsolutePath();
    } else {
        $this->path = 'initial';
    }
}

/**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function preUpload()
{
    if (null !== $this->getFile()) {
        $this->path = $this->getFile()->guessExtension();
    }
}

/**
 * @ORM\PostPersist()
 * @ORM\PostUpdate()
 */
public function upload()
{
    if (null === $this->getFile()) {
        return;
    }

    // check if we have an old image
    if (isset($this->temp)) {
        // delete the old image
        unlink($this->temp);
        // clear the temp image path
        $this->temp = null;
    }

    // you must throw an exception here if the file cannot be moved
    // so that the entity is not persisted to the database
    // which the UploadedFile move() method does
    $this->getFile()->move(
        $this->getUploadRootDir(),
        $this->id.'.'.$this->getFile()->guessExtension()
    );

    $this->setFile(null);
}

/**
 * @ORM\PreRemove()
 */
public function storeFilenameForRemove()
{
    $this->temp = $this->getAbsolutePath();
}

/**
 * @ORM\PostRemove()
 */
public function removeUpload()
{
    if (isset($this->temp)) {
        unlink($this->temp);
    }
}

public function getAbsolutePath()
{
    return null === $this->path
        ? null
        : $this->getUploadRootDir().'/'.$this->id.'.'.$this->path;


 }
}

抱歉,拖了这么久。我以前用身份证号上传过它,但我不能让它再次工作,我也不能让它与文件名一起工作,我有过几次近距离通话,但就我而言。上传目录设置为 777 递归的 chmod

提前致谢

4

1 回答 1

0

我的建议是遵循 Symfony Cookbook 的上传文件示例:http: //symfony.com/doc/current/cookbook/doctrine/file_uploads.html 或使用预先存在的文件上传包。对于该检查:

  1. VichUploaderBundle: https ://github.com/dustin10/VichUploaderBundle
  2. DoctrineExtensions: https ://github.com/l3pp4rd/DoctrineExtensions (Uploadable 是这个包的一部分)
于 2013-07-17T22:29:18.007 回答