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

时间:2019-02-07 06:08:12

标签: php symfony symfony-forms

我已经阅读了文档,但不清楚如何使用symfony表单类型创建以下输入字段。

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

您需要了解上传概念,并尝试实现Symfony shape,以使您正确安全地上传文件。 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;
    }