大家都知道,早期的XMLHttpRequest不支援檔案上傳,一般用第三方js外掛程式或flash,現在可以藉助XMLHttpRequest Level 2 的FormData物件實作二進位檔案上傳,剛好最近工作中遇到了這個需求,所以本文就來跟大家總結下實現的方法,話不多說了,來一起看看詳細的介紹吧。
範例程式碼
@extends('layouts.art') @section('content') <form class="form-horizontal" id="avatar"> {{ csrf_field() }} <p class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">名字</label> <p class="col-sm-8"> <input type="title" class="form-control" id="title" name="title"> </p> </p> <p class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">头像</label> <p class="col-sm-8"> <input type="file" class="form-control" id="title" name="photo"> </p> </p> <p class="form-group"> <p class="col-sm-offset-2 col-sm-10"> <a class="btn btn-default" onclick="uploadInfo()">上传</a> </p> </p> </form> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript"> function uploadInfo() { var formData = new FormData($("#avatar")); $.ajax({ url: "{{url('photo')}}", type: 'POST', data: formData, contentType: false, processData: false, success: function (returndata) { console.log(returndata); }, error: function (returndata) { console.log(returndata); } }); } </script> @endsection
//生成路径,图片存储 $ext = $request->photo->getClientOriginalExtension(); $cover_path = "images/album/covers/" . time() . $ext; $name = "photo".time(); $src = "images/album/photos/". $name .".jpg"; Image::make($request->photo)->save(public_path($src));*/ //批量上传图片 foreach ($request->photo as $key => $value) { //生成路径,图片存储 $prefix = "photo".mt_rand(1,1000); $Origname = $value->getClientOriginalName(); $name = $prefix.$Origname; $src = "images/album/photos/".$name; $realPath = $value->getRealPath(); Storage::disk('uploads')->put($src,file_get_contents($realPath)); }
相關推薦:
以上是laravel和ajax實現檔案上傳功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!