dropzone.js默認是Ajax上傳圖片給服務器,那麼如何獲取到圖片名呢?其實咱們是能夠經過dropzone的success函數獲取到服務器返回的數據php
dropzone.js在HTML的配置以下;json
Dropzone.autoDiscover = false;//防止報"Dropzone already attached."的錯誤 $(".dropzone").dropzone({ url: "__URL__/upload/", addRemoveLinks: true, dictRemoveLinks: "x", dictCancelUpload: "x", paramName:"userImg", maxFiles: 10, maxFilesize: 5, acceptedFiles: "image/*", init: function() { //res爲服務器響應回來的數據 this.on("success", function(file, res) { //將json字符串轉換成json對象 var obj = JSON.parse(res); console.log(obj); if( obj.status == 200 ){ //將服務器獲得的數據生成一個隱藏域。作商品添加的時候就能夠獲取到了 var input = '<input type="hidden" name="'+obj.details.savename+'" value="'+obj.details.savepath+obj.details.savename+'" />'; $('.myform').append(input); }else{ alert('上傳失敗'); } }); this.on("removedfile", function(file) { console.log("File " + file.name + "removed"); }); } });
PHP的代碼以下(Thinkphp代碼):服務器
public function upload() { /* 添加商品 :商品名、商品圖片 */ // 實例化上傳類 $upload = new \Think\Upload(); // 設置附件上傳大小 $upload->maxSize = 3145728 ; // 設置附件上傳類型 $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); //A開發者寫了upload() B開發 // 設置附件上傳目錄 $upload->savePath = './Public/Uploads/'; //返回上傳信息 $info = $upload->uploadOne($_FILES['userImg']); // dump($info);exit; if( !$info ) { // 上傳錯誤提示錯誤信息 // $this->error($upload->getError()); $data['status'] = 404; //錯誤信息 $data['msg'] = $upload->getError(); echo json_encode($data); }else{ // 上傳成功 (圖片路徑、圖片名字) $data['status'] = 200; $data['msg'] = 'UPLOAD SUCCESS'; //圖片原始名字 $data['details']['originName'] = $info['name']; $data['details']['savename'] = $info['savename']; $data['details']['savepath'] = $info['savepath']; echo json_encode($data); } }