Skip to content

Commit 5d1d883

Browse files
author
FreedomKnight
committed
完成基本 file api 以及修改 readme
1 parent 3537e01 commit 5d1d883

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

readme.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ FileEntry API is good way to handle files with Laravel Storage.
66

77
### Initialize FileEntry
88

9+
use \Unisharp\FileEntry\FileEntry;
10+
911
$entry = new FileEntry();
1012

1113
or

src/FileEntry.php

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,66 @@
22

33
namespace Unisharp\FileEntry;
44

5+
use League\Flysystem\FileNotFoundException;
6+
use Symfony\Component\HttpFoundation\File\UploadedFile;
7+
58
class FileEntry
69
{
10+
protected $basepath;
11+
12+
public function __construct($basepath = '/')
13+
{
14+
if (mb_substr($basepath, -1, 1, 'utf8') != '/') {
15+
$basepath .= '/';
16+
}
17+
18+
$this->basepath = $basepath;
19+
}
20+
21+
public function save(UploadedFile $upload_file, $cus_name = null)
22+
{
23+
$file = $this->moveFile($upload_file, $cus_name);
24+
return $file;
25+
}
26+
27+
private function moveFile($upload_file, $cus_name)
28+
{
29+
$suffix = $upload_file->getClientOriginalExtension();
30+
$filename = uniqid() . '.' . $suffix;
31+
if (!empty($cus_name)) {
32+
$filename = $cus_name . '.' .$suffix;
33+
}
34+
\Storage::put(
35+
$this->basepath . $filename,
36+
file_get_contents($upload_file->getRealPath())
37+
);
38+
39+
\File::delete($upload_file->getRealPath());
40+
return $filename;
41+
}
42+
43+
public function response($filename)
44+
{
45+
try {
46+
$path = $this->basepath . $filename;
47+
$file = \Storage::get($path);
48+
$filetime = \Storage::lastModified($path);
49+
$etag = md5($filetime);
50+
$time = date('r', $filetime);
51+
$expires = date('r', $filetime + 3600);
52+
if (trim(\Request::header('If-None-Match'), '\'\"') != $etag ||
53+
new \DateTime(\Request::header('If-Modified-Since')) != new \DateTime($time)
54+
) {
55+
return response($file, 200)->header('Content-Type', \Storage::mimeType($path))
56+
->setEtag($etag)
57+
->setLastModified(new \DateTime($time))
58+
->setExpires(new \DateTime($expires))
59+
->setPublic();
60+
}
61+
62+
return response(null, 304)->setPublic();
63+
} catch (FileNotFoundException $e) {
64+
abort(404);
65+
}
66+
}
767
}

0 commit comments

Comments
 (0)