laravel +vue+element-UI上傳圖片到七牛
阿新 • • 發佈:2018-12-06
element-UI
上傳元件
<el-form-item label="縮圖" prop="photo_id"> <el-upload class="avatar-uploader" action="/photos" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" > <img v-if="site.image" :src="site.image" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-form-item>
JS
部分
handleAvatarSuccess(res) { // console.log(file); this.site.image = res.image_url; this.site.photo_id = res.photo_id; }, beforeAvatarUpload(file) { const isJPG = file.type === 'image/jpeg'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上傳頭像圖片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上傳頭像圖片大小不能超過 2MB!'); } return isJPG && isLt2M; }
我們上傳的檔案預設上傳到storage/app/public
目錄中,我們並不能訪問到這個目錄,我們需要去建立軟鏈指向這個資料夾
php artisan storage:link
報419錯誤,需要自己去排除csrf
防護,在Middleware\VerifyCsrfToken.php
中
protected $except = [
'/photos',//上傳的action
];
public
目錄會生成一個指向的軟鏈目錄資料夾storage
後臺控制器
部分
public function store(Request $request) { if ($request->hasFile('file') and $request->file('file')->isValid()) { //資料驗證 $allow = array('image/jpeg', 'image/png', 'image/gif'); $mine = $request->file('file')->getMimeType(); if (!in_array($mine, $allow)) { return response()->json(['status' => 0, 'msg' => '檔案型別錯誤,只能上傳圖片']); } //檔案大小判斷$filePath $max_size = 1024 * 1024 * 3; $size = $request->file('file')->getClientSize(); if ($size > $max_size) { return response()->json(['status' => 0, 'msg' => '檔案大小不能超過3M']); } //original圖片,上傳到本地 $path = $request->file->store('public/images'); //絕對路徑 $file_path = storage_path('app/') . $path; //儲存到七牛 qiniu_upload($file_path);//呼叫七牛全域性 //插入圖片表 $photo = Photo::create(['image' => 'http://image.holyzq.com/' . basename($file_path)]); return ['photo_id' => $photo->id, 'image' => basename($file_path), 'image_url' => 'http://image.holyzq.com/' . basename($file_path)]; }
}
控制器缺少七牛的SDK和全域性我們進行引入:
composer require qiniu/php-sdk
跑完後, 我們就可以寫一個全域性函數了,在Http/Helpers
下建立一個qiniu.php
內容如下:
// 引入鑑權類
use Qiniu\Auth;
// 引入上傳類
use Qiniu\Storage\UploadManager;
function qiniu_upload($filePath) {
// 需要填寫你的 Access Key 和 Secret Key
$accessKey = "edj5WTd-8sURwN4qZD3YE2U9TDL4skSugNO6yevp";
$secretKey = "4o06NtzXmP0Tu0F8P77Lk4oHSO40zYMae7yXHmUl";
$bucket = "shop";
// 構建鑑權物件
$auth = new Auth($accessKey, $secretKey);
// 生成上傳 Token
$token = $auth->uploadToken($bucket);
// 要上傳檔案的本地路徑
// $filePath = './php-logo.png';
// 上傳到七牛後儲存的檔名
$key = basename($filePath);
// 初始化 UploadManager 物件並進行檔案的上傳。
$uploadMgr = new UploadManager();
// 呼叫 UploadManager 的 putFile 方法進行檔案的上傳。
$uploadMgr->putFile($token, $key, $filePath);
//刪除本地圖片
unlink($filePath);
}
composer.json
中註冊全域性函式
"psr-4": {
"App\\": "app/"
},
"files":[
"app/Http/Helpers/qiniu.php"
]
然後我們重新載入這個命令列輸入
composer dump-autoload
函式載入成功