fjmu's avatar
Level 1

Not possible to manually add an UploadedFile to $request->files

For various reasons, I need to duplicate an uploaded file so that it appears twice on the $request->files but with a new name

I've tried with a Middleware like the code below, tried with set, add, by instantiating UploadedFile, etc.. but none of the 'newname' ones will appear when calling $request->allFiles() later on in a Controller



public function handle($request, Closure $next)
{
        if($request->hasFile('file')){ //True uploaded file

            $request->files->add(['newname1' => \Illuminate\Http\UploadedFile::createFromBase($request->file('file'))]);

            $request->files->set('newname2', \Illuminate\Http\UploadedFile::createFromBase($request->file('file')));

            $request->files->set('newname3', $request->file('file'));

            $fileVar = new \Symfony\Component\HttpFoundation\File\UploadedFile($uploadedFile->getPathname(),
                $uploadedFile->getClientOriginalName(),
                $uploadedFile->getClientMimeType(),
                $uploadedFile->getClientSize(),
                $uploadedFile->getError());

            $request->files->set('newname4', $fileVar);
        }

        return $next($request);
}

However, $request->allFiles() will only show the 'file' which is the one posted from an HTML form but none of the others

0 likes
3 replies
rawilk's avatar

Maybe try creating a temporary file that you could reference in your controller. Just out of curiosity, why would you need to do this? If it's the same exact file, couldn't you just duplicate the file after you upload the first one and do what you need with the duplicate?

1 like
fjmu's avatar
Level 1

@wilk_randall There's mobile framework that always uploads a file with the var name set to 'file'. However, all the code I have written uses a different name. I thought creating a middleware would be the quickest way and would allow me to learn about before filters instead of refactoring my code

However, looks like I've bumped into an open issue of Laravel https://github.com/laravel/framework/issues/10791

(Just found that)

I'll have to refactor my code to stick to 'file'

rawilk's avatar

What framework are you using?

1 like

Please or to participate in this conversation.