laravel+vue+element 下的 后端上传图片较前端上传复杂一些
- 首先vue模版页面,写好模版
<el-form-item label="缩略图" :label-width="formLabelWidth" prop="image">
<el-upload
class="avatar-uploader"
action="/photos"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="form.image" :src="form.image" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
action="/photos"
对应传值的地方,所以对应要建photos控制器和模版
前端:
//图片上传成功之后
handleAvatarSuccess(res, file) {
this.form.image = res.image_url;
},
//图片上传之前
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;
}
前端任务完成
后端:
a. 路由:
//后端上传图片
Route::resource('photos', 'PhotoController')->only('store');
b.控制器:
/***
* 上传图片
* @param Request $request
*/
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 * 2;
$size = $request->file('file')->getClientSize();
if ($size > $max_size) {
return response()->json(['status' => 0, 'msg' => '文件大小不能超过2M']);
}
//original图片
$path = $request->file->store('public/images');
//绝对路径
$file_path = storage_path('app/') . $path;
//保存到七牛
qiniu_upload($file_path);
//这里直接是image 不需要插入其他表格
// //插入图片表
// $photo = Photo::create(['image' => 'http://luvxia.com//' . basename($file_path)]);
return ['status' => 1, 'image' => basename($file_path), 'image_url' => 'http://luvxia.com/' . basename($file_path)];
}
}
c. 辅助函数,先跑七牛命令,再建函数
终端先输入curl -sS https://getcomposer.org/installer | php
再输入php composer.phar require qiniu/php-sdk
--创建HTTP-Helpers-qiniu.php
--引入七牛:
<?php
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;
/**
* 上传到七牛
* @param $filePath 文件的绝对路径
* @return array ['文件信息', '错误信息']
*/
function qiniu_upload($file_path)
{
$accessKey = '';
$secretKey = '';
// 要上传的空间
$bucket = '';
// 构建鉴权对象
$auth = new Auth($accessKey, $secretKey);
// 生成上传 Token
$token = $auth->uploadToken($bucket);
// 上传到七牛后保存的文件名
$key = basename($file_path);
// 初始化 UploadManager 对象并进行文件的上传
$uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传
$uploadMgr->putFile($token, $key, $file_path);
unlink($file_path);
}
d.注册辅助函数,在composer.json
中注册函数,autoload
中加files
"autoload": {
"files": [
"app/Http/Helpers/qiniu.php"
]
}
e. 执行辅助函数,终端输入命令
composer dump-autoload
上传完成