簡體   English   中英

Symfony3從控制器發送表單

[英]Symfony3 Sending a Form from the Controller

編輯:

我找到了$ form-> submit()方法並嘗試了一下:

file_put_contents(__DIR__ . "/../../../web/uploads/img/tmp.jpeg", file_get_contents($output['images']['show']));

$image = new Image();;

$form = $this->createForm(ImageType::class, $image);

$form->submit( __DIR__ . "/../../../web/uploads/img/tmp.jpeg" );

if ($form->isSubmited() && $form->isValid()) {
    ...
}

但顯然該表格無效,因為它沒有超出條件

編輯2:我為ImageType禁用了csrf_protection,但是它仍然無效,Xdebug告訴我該路徑無效,但是如果我嘗試通過一種形式從同一路徑上載相同的圖像,則可以正常工作...


我正在一個項目中有這個Image實體:

class Image
{
    //... Attributes, setters and getters        

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null === $this->file) {
            return;
        }
        $this->url = $this->file->guessExtension();
        $this->alt = $this->file->getClientOriginalName();
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if (null === $this->file) {
            return;
        }
        if (null !== $this->tempFilename) {
            $oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this->tempFilename;
            if (file_exists($oldFile)) {
                unlink($oldFile);
            }
        }
        $this->file->move(
            $this->getUploadRootDir(),
            $this->id.'.'.$this->url
        );
    }

    /**
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file)
    {
        $this->file = $file;
        if (null !== $this->url) {
            $this->tempFilename = $this->url;
            $this->url = null;
            $this->alt = null;
        }
    }
}

當我通過表單從本地文件上傳圖像時,該方法效果很好。

但我還需要能夠從API下載文件:

file_put_contents(__DIR__ . "/../../../web/uploads/img/tmp.jpeg", file_get_contents($output['images']['show']));

$image = new Image();

$file = new UploadedFile(__DIR__ . "/../../../web/uploads/img/tmp.jpeg", 'tmp.jpeg');

$image->setFile($file);

據我了解,一旦我堅持$ image,preUpload()和upload()都將被調用,但是當我這樣做時會出現此錯誤:

“由於未知錯誤,未上傳文件“ tmp.jpeg”。“

這似乎是由upload()的$ this-> file-> move()部分觸發的

我很確定這是因為UploadedFile的isValid()函數僅在文件已使用HTTP上傳並在move()開始時被調用時才返回true。

我的問題有什么解決方法嗎? 我對Symfony相當陌生(一般來說,對編碼的興趣也有所減少),所以我不確定自己的選擇是什么。

有沒有辦法欺騙$ image來“思考” $ file來自表單?

自從我專門執行此操作已經有一段時間了,但是我認為,如果要使其有效,則在手動創建UploadedFile時必須在構造函數中具有模仿類型。

$file = new UploadedFile(__DIR__ . "/../../../web/uploads/img/tmp.jpeg", 'tmp.jpeg','image/jpeg');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM