1. 引入CSS & JS檔案
<link href="http://hayageek.github.io/jQuery-Upload-File/4.0.10/uploadfile.css" rel="stylesheet"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><br > <script src="http://hayageek.github.io/jQuery-Upload-File/4.0.10/jquery.uploadfile.min.js"></script>
2.在Body區間內新增div
<code class="prettyprint"><div id="fileuploader">Upload</div>
3. 初始化元件在 document
ready.
<code class="prettyprint"><script> $(document).ready(function() { $("#fileuploader").uploadFile({ url:"YOUR_FILE_UPLOAD_URL", //上傳的路徑位置 fileName:"myfile" //此為 $_FILES 取得的物件名稱 }); }); </script>
4.在server新增上傳PHP
<?php $output_dir = "uploads/"; //設定上傳路徑 if(isset($_FILES["myfile"])) { $ret = array(); $error =$_FILES["myfile"]["error"]; //錯誤訊息 if(!is_array($_FILES["myfile"]["name"])) //單一檔案 { $fileName = $_FILES["myfile"]["name"]; //檔案名稱 move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);//1:原始檔案名稱2:路徑/檔名 $ret[]= $fileName; } else //多檔傳送 { $fileCount = count($_FILES["myfile"]["name"]); for($i=0; $i < $fileCount; $i++) { $fileName = $_FILES["myfile"]["name"][$i]; move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName); $ret[]= $fileName; } } echo json_encode($ret); } ?>eee
結果顯示
增加上傳後修改檔案名稱
1.依樣引入JS & CSS
2.宣告DIV
<div class="modal-body" id="OrderInfoID" style="height: 180px"> <div class="col-xs-12 col-sm-12 col-md-12" > <label>身分證正面</label> <div id="mulitplefileuploader" onclick="addbtn()">上傳檔案</div> </div> </div>
3.設定上傳參數
<script> var settings; var RelTtrSnoID; //此為要修改的檔名 var uploadObj; //取得陣列索引 function GetRetTtrSno(TempI) { $('.ajax-file-upload-container').html(''); RelTtrSnoID = arcTtrNo[TempI]["RelTtrSno"];//取得要修改的檔名 settings = { url:'127.0.0.1/upload.php?title='+RelTtrSnoID+'.jpg', //在網址後方加入title 讓PHP端取得標題 method: "POST", dragDrop:false, multiple:false, allowedTypes:"jpg,png,gif,jpeg", fileName: "myfile", showDelete:false, returnType:"json", onSubmit: function(files,xhr) { }, onSuccess:function(files,data,xhr) { if(data == RelTtrSnoID+'.jpg' ) //如果檔案上傳成功並且回傳修改後檔名 { alert("身分證正面上傳成功"); } }, onError: function(files,status,errMsg) { }, afterUploadAll: function() { } } uploadObj = $("#mulitplefileuploader").uploadFile(settings); } } </script>
4.server端PHP
<?php header('Content-Type: text/plain; charset=utf-8'); $output_dir = "UpLoadPic/"; if(isset($_FILES["myfile"])) { $FileNewName = $_GET['title']; //取得檔案標題 $ret = array(); $error = $_FILES["myfile"]["error"]; if(!is_array($_FILES["myfile"]["name"])) //single file { move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$FileNewName); //將名稱修改為取得的檔案標題 $ret[] = $FileNewName; } else { $fileCount = count($_FILES["myfile"]["name"]); for($i = 0; $i < $fileCount; $i++) { move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$FileNewName); $ret[] = $FileNewName; } } echo json_encode($ret); } ?>
先取得要修改的名稱:E201604110008
上傳檔案完成
server 端查看圖片
我們可以看到檔案已傳至SERVER端