模板核心代碼
<!DOCTYPE html> <html> <head> <title>ajax上傳多圖片並且預覽</title> <!-- 只是為了引用按鈕的樣式 --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <form method="post" enctype="multipart/form-data"> <div style="margin-left:20%;margin-top: 100px;"> <span id="showlist" style="margin-left: 25px;"></span> <span style="display:inline-block;height: 30px;position: relative;top:0px;left:0px;"> <a style="display: inline-block;" class="btn btn-info">上傳圖片</a> <input type="file" name="img_src" style="width: 100px;border: 1px solid red;position: absolute;top:0px;left: 0px;height: 30px;opacity: 0;" onchange="upload(this)"> </span> </div> </form> </body> </html>
JS核心代碼:
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> function upload(obj) { if( obj.value == "" ) { alert('文件上傳出錯'); return; } // 實例化一個對象 var formdata = new FormData(); formdata.append("img" , $(obj)[0].files[0]);//獲取文件 $.ajax({ type : 'post', url : '/index/index/upimg', // 上傳圖片的接口地址 data : formdata, cache : false, processData : false, // 不處理發送的數據,因為data值是Formdata對象,不需要對數據做處理 contentType : false, // 不設置Content-type請求頭 success : function(response){ console.log(response); var html = '<div style="position: relative;margin-right: 20px;margin-bottom: 15px;width: 132px;display: inline-block;border: 1px solid #CCC;background:#EEE;">' +'<span style="display: block;width: 120px;height: 80px;border: 1px solid #F2F1F0;margin: 5px;overflow: hidden;">' +'<img src="'+response+'" style="width: 100%;" />' +'</span>' +'<input type="hidden" name="imgs[]" value="'+response+'" />' +'<a onclick="delImg(this);" style="z-index: 10;display: block;top: -8px;cursor:pointer;right: -8px;position:absolute;width: 20px;height: 20px;background: #CCC;border-radius:100%;text-align:center;line-height: 20px;border: 1px solid #C1C1C1;color: #555;">X</a>' +'</div>'; $('#showlist').append(html); }, error : function(){ } }); } function delImg(obj) {
// 向上找到父元素刪除 $(obj).parent('div').remove(); } </script>
服務器端核心代碼:
// 上傳圖片接口 public function upimg() { // 第一步 接收上傳的圖片資源 $file = request()->file('img'); if($file){ // 第二步 驗證並且上傳到我們項目的/public/uploads/目錄下 $info = $file->validate(['size'=>1567800,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads'); // 第三步 判斷圖片是否上傳成功 if($info){ // 第四步 成功上傳后 獲取上傳信息 $img_src = '/uploads/'.$info->getSaveName(); echo $img_src; //返回ajax請求 }else{ // 第四步 上傳失敗獲取錯誤信息 $this->error($file->getError()); } } }