美文网首页程序员
laravel多图异步上传

laravel多图异步上传

作者: 闲睡猫 | 来源:发表于2019-03-18 20:40 被阅读0次

    创建路由

    routes/web.php添加:

    Route::get('image-upload', 'HomeController@imageUpload');
    Route::post('image-upload', 'HomeController@imageUploadPost')->name('image.upload');
    

    创建控制器

    app/Http/Controllers/HomeController.php

    <?php namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    
    class HomeController extends Controller
    {
        public function imageUpload()
        {
            return view('imageUpload');
        }
    
        public function imageUploadPost(Request $request)
        {
            request()->validate([
                'uploadFile' => 'required',
            ]);
            foreach ($request->file('uploadFile') as $key => $value) {
                $imageName = $value->getClientOriginalName();
                $value->move(public_path('images'), $imageName);
            }
            return response()->json(['success'=>'上传成功']);
        }
    }
    

    创建视图文件

    resources/views/imagesUpload.blade.php

    
    
    
        <title>laravel异步上传多图</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script><script src="https://cdn.staticfile.org/jquery.form/4.2.2/jquery.form.min.js"></script><style type="text/css">
            input[type=file] {
                display: inline;
            }
            #image_preview {
                padding: 10px;
            }
            #image_preview img {
                width: 200px;
                padding: 5px;
            }
        </style>
    <div class="container mt-5">
        <h3>laravel5.7异步上传多图</h3>
        <form action="%7B%7B%20route('images.upload')%20%7D%7D" method="post" enctype="multipart/form-data">
            {{ csrf_field() }}
            <input type="file" id="uploadFile" name="uploadFile[]" multiple><input type="submit" class="btn btn-success btn-sm" name="submitImage" value="上传">
    </form>
        <br><div id="image_preview"></div>
    </div>
    
    <script type="text/javascript">
        $("#uploadFile").change(function () {
            $('#image_preview').html("");
            let total_file = document.getElementById("uploadFile").files.length;
            for (let i = 0; i < total_file; i++) {
                $('#image_preview').append("<img src='" + URL.createObjectURL(event.target.files[i]) + "'>");
            }
        });
        $('form').ajaxForm(function () {
            alert("上传成功");
        });
    </script>
    

    演示

    访问:http://localhost/image-upload

    多图上传

    查看public/images,即可看到上传的图片

    相关文章

      网友评论

        本文标题:laravel多图异步上传

        本文链接:https://www.haomeiwen.com/subject/spqimqtx.html