如何使用symfony的表单类型创建多个文件上传字段?

问题描述 投票:0回答:2

我已经通过文件走了,但目前尚不清楚的是,我们如何创建以下使用symfony的formtype输入字段。

<input id="image-file" name="files[]" type="file" multiple>

php symfony symfony-forms
2个回答
0
投票

尝试这样的:

use Symfony\Component\Form\Extension\Core\Type\FileType;

class ImageFile extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('images', FileType::class, [
                'multiple' => true,
                'attr'     => [
                    'accept' => 'image/*',
                    'multiple' => 'multiple'
                ]
            ])
        ;
    }
}

改变你的“形象”的财产,以“图片”属性:

/**
 * Set images
 *
 * @param string $images
 *
 * @return satelliteImage[]
 */
public function setImages($images)
{
    $this->images = $images;

    return $this;
}

/**
 * Get images
 *
 * @return string
 */
public function getImages()
{
    return $this->image;
}

public function addImage($image)
{
    $this->images[] = $image;

    return $this;
}

0
投票

你需要了解上传概念,并尝试实施Symfony的造型让你正确,安全地上传文件。 Upload File with Symfony 该政党成员应该帮助你太Upload multiple files with Symfony 4 对于没有框架的PHP谨

define("UPLOAD_DIR", "/path/to/uploaded_file/");

if (!empty($_FILES["files"])) {
    $myFile = $_FILES["files"];

    if ($myFile["error"] !== UPLOAD_ERR_OK) {
        echo "<p>An error occurred.</p>";
        exit;
    }

    // ensure a safe filename
    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

    // don't overwrite an existing file
    $i = 0;
    $parts = pathinfo($name);
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }

    // preserve file from temporary directory
    $success = move_uploaded_file($myFile["tmp_name"],
        UPLOAD_DIR . $name);
    if (!$success) {
        echo "<p>Unable to save file.</p>";
        exit;
    }
© www.soinside.com 2019 - 2024. All rights reserved.