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

吾爱主题 阅读:221 2021-11-25 15:51:00 评论:0

1、定义路由

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

2、编写 controller 层

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 /**       * 返回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、查看接口返回

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

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 <template>      <div class= "test" style= "padding:100px 0px 1000px 0px;" >          <div>                               <input type= "file" id= "file" name= "file" />              <a @click= "upload()" href= "javascript:;" rel= "external nofollow" >上传</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 + '/' + _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文件上传功能的示例的文章就介绍到这了,更多相关laravel 阿里云oss文件上传内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/zion0707/p/12118661.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容