Search code examples
symfonyfilenamesemail-attachments

Why getClientOriginalName() doesn't work to get the original name of a uploaded file?


To attach uploaded files to an email, I use the function getClientOriginalName() and in the receipted email, the name of the file is always the basename, without extension.

I use a code I've found in https://hotexamples.com/site/redirect?url=https%3A%2F%2Fgithub.com%2Falexander-schranz%2Fsulu-website-user-bundle I have tried multiple way to write the search of the original name, and I found always the same basename My function is :

public function send($from, $to, $sujet, $body, $attachments = [])
    {
    $message = new \Swift_Message($sujet, $body);
    $message->setFrom($from);
    $message->setTo($to);
    if (count($attachments) > 0) {
        foreach ($attachments as $file) {
            switch ($file) {
...
                    case $file instanceof UploadedFile:
                        $nomfic = $file->getClientOriginalName();             
                        break;
                        }
    $message->attach(\Swift_Attachment::fromPath($path),$nomfic);

The beginning of the dump of the attachment is :

 0 => UploadedFile {#16 ▼
    -test: false
    -originalName: "etiquettes.pdf"
    -mimeType: "application/pdf"
    -error: 0
    path: "/tmp"
    filename: "php4Koz9N"
    basename: "php4Koz9N"
    pathname: "/tmp/php4Koz9N"

I hope to have "etiquettes.pdf" instead of "php4Koz9N" !!

What can I do ?


Solution

  • getClientOriginalName returns name uploaded file in the browser (warning! it's unsafe). The real file is in /tmp/phpXXXXX.

    So, your code may be ...

    <?php
    
    $attach = \Swift_Attachment::fromPath($uploadedfile->getRealPath(), $uploadedfile->getMimeType());
    $attach->setFilename($uploadedfile->getClientOriginalName()); # Only if you rely in your client. That is, never!
    $message->attach($attach);