为什么 getClientOriginalName() 无法获取上传文件的原始名称?

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

为了将上传的文件附加到电子邮件,我使用函数 getClientOriginalName() 并且在收到的电子邮件中,文件名始终是基本名称,没有扩展名。

我使用了在 https://hotexamples.com/site/redirect?url=https%3A%2F%2Fgithub.com%2Falexander-schranz%2Fsulu-website-user-bundle 中找到的代码 我尝试了多种方式来编写原始名称的搜索,但我发现总是相同的基本名称 我的功能是:

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);

附件转储的开头是:

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

我希望有 "etiquettes.pdf" 而不是 "php4Koz9N" !!

我能做什么?

getClientOriginalName returns 在浏览器中命名上传的文件(警告!这是不安全的)。真正的文件在/tmp/phpXXXXX

所以,您的代码可能是...

<?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);