Vue+thinkphp5.1+axios實現文件上傳
本文實例為大家分享了使用thinkphp5.1 + Vue+axios+實現文件上傳,供大家參考,具體內容如下
前言使用thinkphp5.1 + Vue+axios+實現文件上傳
一.頁面代碼
<!DOCTYPE html><html><head> <meta charset='utf-8'> <title>上傳Demo</title> <style>.fileBtn{ width: 180px; height: 36px; line-height: 36px; background: skyblue; border-radius: 5px; display: block; text-align: center; color: white;}[v-cloak] { display: none;} </style> <script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'></script> <script src='https://unpkg.com/axios/dist/axios.min.js'></script></head><body><div id='app'> <h1 v-cloak>{{message}}</h1> <form><input type='file' name='file' ref='file' v-on:change='upload' /><label for='file' class='fileBtn'>上傳</label> </form></div></body></html><script> var vue = new Vue({el:’#app’,data:{ message:’文件上傳’,},methods:{ upload:function(file) {console.log(file.target.files[0]);var forms = new FormData()var configs = { headers:{’Content-Type’:’multipart/form-data;charse=UTF-8’}};forms.append(’file’,file.target.files[0]);axios.post(’http://127.0.0.1/index/index/upload’, forms,configs) .then(function (response) {if (response.data.code == 0) { alert(’文件上傳成功’);} else { alert(’文件上傳失敗’);}file.target.value = ’’; }) .catch(function (error) {console.log(error); }); }} });</script>
二、解決接口跨域問題
這里使用的apache 2.4.8,找到httpd.conf ,添加一行配置:
Header set Access-Control-Allow-Origin *
三.后端處理上傳部分
/** * 文件上傳方法校驗 */ public function upload() {try{ $file = request()->file(’file’); if (empty($file)) {echo json_encode([’code’ => 1,'msg' => ’請選擇上傳文件’],JSON_UNESCAPED_UNICODE);exit; } // 移動到框架應用根目錄/uploads/ 目錄下 $info = $file->move( ’../uploads’); if($info){// 成功上傳后 獲取上傳信息// 輸出 jpgecho json_encode([’code’ => 0,'msg' => ’succcess’],JSON_UNESCAPED_UNICODE);exit; }else{// 上傳失敗獲取錯誤信息echo json_encode([’code’ => 1,'msg' => ’error’],JSON_UNESCAPED_UNICODE);exit; }} catch (Exception $e) { echo json_encode([’code’ => 1,'msg' => ’error’],JSON_UNESCAPED_UNICODE);exit;}}
四.實際效果
測試成功!
關于vue.js的學習教程,請大家點擊專題vue.js組件學習教程、Vue.js前端組件學習教程進行學習。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. phpstudy apache開啟ssi使用詳解2. CentOS郵件服務器搭建系列—— POP / IMAP 服務器的構建( Dovecot )3. .NET SkiaSharp 生成二維碼驗證碼及指定區域截取方法實現4. IntelliJ IDEA創建web項目的方法5. 存儲于xml中需要的HTML轉義代碼6. docker容器調用yum報錯的解決辦法7. django創建css文件夾的具體方法8. MyBatis JdbcType 與Oracle、MySql數據類型對應關系說明9. ASP中實現字符部位類似.NET里String對象的PadLeft和PadRight函數10. javascript xml xsl取值及數據修改第1/2頁
