laravel 实现阿里云oss文件上传功能的示例

// 阿里云文件储存 Route::group(['prefix'=>'aliyun'], function(){ Route::get('sign', 'AliyunController@sign'); });

2、编写 controller 层

/** * 返回OSS的签名验证 * @return JSON 签名信息 */ public function sign(Request $request) { //初始化一下必要的请求数据 $id = 'xxx'; //AccessKeyId $key = 'xxx'; //AccessKeySecret $host = '//xxx.oss-cn-shenzhen.aliyuncs.com'; //OSS库地址 $cdn_host = "//img.xxx.com"; //真实的访问地址 $dir = 'test/'; //上传目录设置 $callbackUrl = url('upload/callback'); //上传回调的地址 //上传回调的参数,callbackUrl地址,callbackBody回调接收的参数,callbackBodyType通过POST调用的回调函数,所以要设置这个头 $callback_param = array( 'callbackUrl' => $callbackUrl, 'callbackBody' => 'filename=${object}&size=${size}&mimeType =${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}', 'callbackBodyType' => "application/x-www-form-urlencoded" ); $callback_string = json_encode($callback_param); //转换成json格式 $base64_callback_body = base64_encode($callback_string); //要返回的回调函数参数信息 //设置过期时间 $now = time(); $expire = 60 * 60 * 2; //设置该policy超时时间是 2小时. 即这个policy过了这个有效时间,将不能访问,这里可以根据自己的token过期时间来设置 $end = $now + $expire; $expiration = $this->gmt_iso8601($end); //进行时间格式的转换 //处理上传限制条件 //最大文件大小.用户可以自己设置 $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000); $conditions[] = $condition; //设定文件大小 //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录 $start = array(0 => 'starts-with', 1 => '$key', 2 => $dir); $conditions[] = $start; //必须以设定的目录开头,防止上传错误 $arr = array('expiration' => $expiration, 'conditions' => $conditions); $policy = json_encode($arr); $base64_policy = base64_encode($policy); //要返回的上传限制参数 //签名信息 $string_to_sign = $base64_policy; $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true)); //要返回的签名信息 //设置返回信息 $response = array( 'accessid' => $id, //accessid 'host' => $host, //上传地址 'cdn_host' => $cdn_host, //真实的访问地址 'policy' => $base64_policy, //上传文件限制 'signature' => $signature, //签名信息 'expire' => $end, //失效时间 'callback' => $base64_callback_body, //上传回调参数 'dir' => $dir //上传的目录 ); return response()->json([ 'code' => 0, 'msg' => 'success', 'data' => $response ]); } //格式化时间,格式为2020-07-07T23:48:43Z public function gmt_iso8601($time) { $dtStr = date("c", $time); $pos = strpos($dtStr, '+'); $expiration = substr($dtStr, 0, $pos); return $expiration . "Z"; }

3、查看接口返回

laravel 实现阿里云oss文件上传功能的示例

4、前端界面及操作编写,这里采用的是 vue

<template> <div> <div> <input type="file" /> <a @click="upload()" href="javascript:;" >上传</a> </div> </div> </template> <script> export default { data(){ return { } }, mounted() { this.getOssToken(); }, methods: { //获取上传通行证 getOssToken(){ var _self = this; this.axios.get('/aliyun/sign').then((res)=>{ var data = res.data; if(data.code==0){ _self.aliyunOssToken = data.data; }else{ _self.$message.warning(data.msg); } }); }, upload(){ var _self = this; var getSuffix = function (fileName) { var pos = fileName.lastIndexOf("."); var suffix = ''; if (pos != -1) { suffix = fileName.substring(pos); } return suffix; } var file = $("#file").val(); if (file.length == 0) { alert("请选择文件"); } var oFileName = file.lastIndexOf('\\'); var oFileName = file.substr(oFileName+1); var fileName = oFileName.lastIndexOf('.'); var fileName = oFileName.substr(0,fileName); console.log(fileName); var filename = new Date().getTime() + getSuffix(file); var formData = new FormData(); //注意formData里append添加的键的大小写 formData.append('key', _self.aliyunOssToken.dir + filename); //存储在oss的文件路径 formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId formData.append('policy', _self.aliyunOssToken.policy); //policy formData.append('Signature', _self.aliyunOssToken.signature); //签名 formData.append("file", $("#file")[0].files[0]); formData.append('success_action_status', 200); //成功后返回的操作码 var url = _self.aliyunOssToken.host; var fileUrl = _self.aliyunOssToken.cdn_host +'https://www.jb51.net/'+ _self.aliyunOssToken.dir + filename; $.ajax({ url: url, type: 'POST', data: formData, // async: false, cache: false, contentType: false, processData: false, success: function (data) { console.log(fileUrl); console.log(data); }, error: function (data) { console.log(data); } }); } } } </script>

5、点击上传按钮,浏览器控制台输出链接,访问该链接,即可看到该图片

laravel 实现阿里云oss文件上传功能的示例

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwwssd.html