laravel 中 文件上傳的使用


 

 

1.  laravel  文件上傳

    public function store(Request $request)
    {

        // dd($request->file());

        if ($request->hasFile('picture')) {
            $picture = $request->file('picture');
            if (!$picture->isValid()) {
                abort(400, '無效的上傳文件');
            }
            // 文件擴展名
            $extension = $picture->getClientOriginalExtension();
            // 文件名
            $fileName = $picture->getClientOriginalName();
            // 生成新的統一格式的文件名
            $newFileName = md5($fileName . time() . mt_rand(1, 10000)) . '.' . $extension;
            // 圖片保存路徑
            $savePath = 'images/' . $newFileName;
            // Web 訪問路徑
            $webPath = '/storage/'. $savePath;

            // 將文件保存到本地 storage/app/public/images 目錄下,先判斷同名文件是否已經存在,如果存在直接返回
            if (Storage::disk('public')->has($savePath)) {
                return response()->json(['path' => $webPath]);
            }
            // 否則執行保存操作,保存成功將訪問路徑返回給調用方
            if ($picture->storePubliclyAs('images', $newFileName, ['disk' => 'public'])) {
                return response()->json(['path' => $webPath]);
            }
            abort(500, '文件上傳失敗');
        } else {
            abort(400, '請選擇要上傳的文件');
        }
    }

 

<template>
    <div class="form-group">
        <label for="picture">上傳一張圖片</label>
        <input type="file" class="form-control-file" id="picture" ref="picture" v-on:change="uploadFile"/>
    </div>
</template>

<script>
    export default {
        methods: {
            uploadFile() {
                let formData = new FormData();
                formData.append('picture', this.$refs.picture.files[0]);
                axios.post(
                    '/form/store',
                    formData,
                    {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }
                ).then(function (response) {
                    console.log(response);
                }).catch(function (error) {
                    console.log(error);
                });
            }
        }
    }
</script>

 

 

2. 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM