@@ -31,6 +31,7 @@ class BinaryFileResponse extends Response
31
31
* @var File
32
32
*/
33
33
protected $ file ;
34
+ protected ?\SplTempFileObject $ tempFileObject = null ;
34
35
protected $ offset = 0 ;
35
36
protected $ maxlen = -1 ;
36
37
protected $ deleteFileAfterSend = false ;
@@ -65,15 +66,18 @@ public function __construct(\SplFileInfo|string $file, int $status = 200, array
65
66
*/
66
67
public function setFile (\SplFileInfo |string $ file , string $ contentDisposition = null , bool $ autoEtag = false , bool $ autoLastModified = true ): static
67
68
{
69
+ $ isTemporaryFile = $ file instanceof \SplTempFileObject;
70
+ $ this ->tempFileObject = $ isTemporaryFile ? $ file : null ;
71
+
68
72
if (!$ file instanceof File) {
69
73
if ($ file instanceof \SplFileInfo) {
70
- $ file = new File ($ file ->getPathname ());
74
+ $ file = new File ($ file ->getPathname (), ! $ isTemporaryFile );
71
75
} else {
72
76
$ file = new File ((string ) $ file );
73
77
}
74
78
}
75
79
76
- if (!$ file ->isReadable ()) {
80
+ if (!$ file ->isReadable () && ! $ isTemporaryFile ) {
77
81
throw new FileException ('File must be readable. ' );
78
82
}
79
83
@@ -83,7 +87,7 @@ public function setFile(\SplFileInfo|string $file, string $contentDisposition =
83
87
$ this ->setAutoEtag ();
84
88
}
85
89
86
- if ($ autoLastModified ) {
90
+ if ($ autoLastModified && ! $ isTemporaryFile ) {
87
91
$ this ->setAutoLastModified ();
88
92
}
89
93
@@ -301,19 +305,25 @@ public function sendContent(): static
301
305
}
302
306
303
307
$ out = fopen ('php://output ' , 'w ' );
304
- $ file = fopen ($ this ->file ->getPathname (), 'r ' );
308
+
309
+ if ($ this ->tempFileObject ) {
310
+ $ file = $ this ->tempFileObject ;
311
+ $ file ->rewind ();
312
+ } else {
313
+ $ file = new \SplFileObject ($ this ->file ->getPathname (), 'r ' );
314
+ }
305
315
306
316
ignore_user_abort (true );
307
317
308
318
if (0 !== $ this ->offset ) {
309
- fseek ( $ file, $ this ->offset );
319
+ $ file-> fseek ( $ this ->offset );
310
320
}
311
321
312
322
$ length = $ this ->maxlen ;
313
- while ($ length && !feof ( $ file )) {
323
+ while ($ length && !$ file-> eof ( )) {
314
324
$ read = $ length > $ this ->chunkSize || 0 > $ length ? $ this ->chunkSize : $ length ;
315
325
316
- if (false === $ data = fread ( $ file, $ read )) {
326
+ if (false === $ data = $ file-> fread ( $ read )) {
317
327
break ;
318
328
}
319
329
while ('' !== $ data ) {
@@ -329,9 +339,8 @@ public function sendContent(): static
329
339
}
330
340
331
341
fclose ($ out );
332
- fclose ($ file );
333
342
} finally {
334
- if ($ this ->deleteFileAfterSend && is_file ($ this ->file ->getPathname ())) {
343
+ if (null === $ this -> tempFileObject && $ this ->deleteFileAfterSend && is_file ($ this ->file ->getPathname ())) {
335
344
unlink ($ this ->file ->getPathname ());
336
345
}
337
346
}
0 commit comments