|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Http\Controllers; |
| 4 | + |
| 5 | +use Illuminate\Http\Request; |
| 6 | + |
| 7 | +use App\Http\Requests; |
| 8 | + |
| 9 | +class AttachmentsController extends Controller |
| 10 | +{ |
| 11 | + /** |
| 12 | + * AttachmentsController constructor. |
| 13 | + */ |
| 14 | + public function __construct() |
| 15 | + { |
| 16 | + $this->middleware('auth', ['except' => 'show']); |
| 17 | + } |
| 18 | + |
| 19 | + /** |
| 20 | + * Store a newly created resource in storage. |
| 21 | + * |
| 22 | + * @param \Illuminate\Http\Request $request |
| 23 | + * @return \Illuminate\Http\Response |
| 24 | + */ |
| 25 | + public function store(Request $request) |
| 26 | + { |
| 27 | + $attachments = []; |
| 28 | + |
| 29 | + if ($request->hasFile('files')) { |
| 30 | + $files = $request->file('files'); |
| 31 | + |
| 32 | + foreach($files as $file) { |
| 33 | + $filename = str_random().filter_var($file->getClientOriginalName(), FILTER_SANITIZE_URL); |
| 34 | + |
| 35 | + $payload = [ |
| 36 | + 'filename' => $filename, |
| 37 | + 'bytes' => $file->getClientSize(), |
| 38 | + 'mime' => $file->getClientMimeType() |
| 39 | + ]; |
| 40 | + |
| 41 | + $file->move(attachments_path(), $filename); |
| 42 | + |
| 43 | + $attachments[] = ($id = $request->input('article_id')) |
| 44 | + ? \App\Article::findOrFail($id)->attachments()->create($payload) |
| 45 | + : \App\Attachment::create($payload); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return response()->json($attachments, 200, [], JSON_PRETTY_PRINT); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Remove the specified resource from storage. |
| 54 | + * |
| 55 | + * @param \App\Attachment $attachment |
| 56 | + * @return \Illuminate\Http\Response |
| 57 | + */ |
| 58 | + public function destroy(\App\Attachment $attachment) |
| 59 | + { |
| 60 | + $path = attachments_path($attachment->name); |
| 61 | + |
| 62 | + if (\File::exists($path)) { |
| 63 | + \File::delete($path); |
| 64 | + } |
| 65 | + |
| 66 | + $attachment->delete(); |
| 67 | + |
| 68 | + return response()->json($attachment, 200, [], JSON_PRETTY_PRINT); |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Display the specified resource. |
| 73 | + * |
| 74 | + * @param $file |
| 75 | + * @return \Illuminate\Contracts\Routing\ResponseFactory |
| 76 | + */ |
| 77 | + public function show($file) |
| 78 | + { |
| 79 | + $path = attachments_path($file); |
| 80 | + |
| 81 | + if (! \File::exists($path)) { |
| 82 | + abort(404); |
| 83 | + } |
| 84 | + |
| 85 | + $image = \Image::make($path); |
| 86 | + |
| 87 | + return response($image->encode('png'), 200, [ |
| 88 | + 'Content-Type' => 'image/png' |
| 89 | + ]); |
| 90 | + } |
| 91 | +} |
0 commit comments