当前位置 知且行 php 正文 下一篇:

laravel多图异步上传

创建路由

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

<!DOCTYPE html>
<html>
<head>
    <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>
</head>
<body>
<div class="container mt-5">
    <h3>laravel5.7异步上传多图</h3>
    <form action="{{ route('images.upload') }}" 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>
</body>
<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>
</html>

演示

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

多图上传

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

转载必须注明出处:https://www.zhiqiexing.com/83.html

关于我

我希望能成为一个认真、有趣、创造更多价值的人
关注微信
微信扫一扫关注我

微信扫一扫关注我

返回顶部