Skip to content

Commit 02543e4

Browse files
committed
added basic information about the form file type
1 parent 3783dfd commit 02543e4

File tree

1 file changed

+67
-1
lines changed

1 file changed

+67
-1
lines changed

reference/forms/types/file.rst

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,70 @@
44
file Field Type
55
===============
66

7-
See :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\FileType`.
7+
The ``file`` type represents a file input in your form.
8+
9+
+-------------+---------------------------------------------------------------------+
10+
| Rendered as | ``input`` ``file`` field |
11+
+-------------+---------------------------------------------------------------------+
12+
| Options | none |
13+
+-------------+---------------------------------------------------------------------+
14+
| Parent type | :doc:`form</reference/forms/types/field>` |
15+
+-------------+---------------------------------------------------------------------+
16+
| Class | :class:`Symfony\\Component\\Form\\Extension\\Core\\Type\\FileType` |
17+
+-------------+---------------------------------------------------------------------+
18+
19+
Basic Usage
20+
-----------
21+
22+
Let's say you have this form definition:
23+
24+
.. code-block:: php
25+
26+
$builder->add('attachment', 'file');
27+
28+
.. caution::
29+
30+
Don't forget to add the ``enctype`` attribute in the form tag: ``<form
31+
action="#" method="post" {{ form_enctype(form) }}>``.
32+
33+
When the form is submitted, the document element will be an instance of
34+
:class:`Symfony\\Component\\HttpFoundation\\File\\UploadedFile`. It can be
35+
used to move the `attachment` file to a permanent location:
36+
37+
.. code-block:: php
38+
39+
use Symfony\Component\HttpFoundation\File\UploadedFile;
40+
41+
public function uploadAction()
42+
{
43+
// ...
44+
45+
if ($form->isValid()) {
46+
$form['attachment']->move($dir, $file);
47+
48+
// ...
49+
}
50+
51+
// ...
52+
}
53+
54+
The ``move()`` method takes a directory and a file name as arguments::
55+
56+
// use the original file name
57+
$file->move($dir, $this->getOriginalName());
58+
59+
// compute a random name and try to guess the extension (more secure)
60+
$extension = $file->guessExtension();
61+
if (!$extension) {
62+
// extension cannot be guessed
63+
$extension = 'bin';
64+
}
65+
$file->move($dir, rand(1, 99999).'.'.$extension);
66+
67+
Using the original name via ``getOriginalName()`` is not safe as it can have
68+
been manipulated by the end-user. Moreover, it can contain characters that are
69+
not allowed in file names. You should sanitize the name before using it
70+
directly.
71+
72+
Read the :doc:`cookbook </cookbook/doctrine/file_uploads>` for an example of
73+
how to manage a file upload associated with a Doctrine entity.

0 commit comments

Comments
 (0)