服务器之家

服务器之家 > 正文

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

时间:2021-11-25 15:51     来源/作者:Zion0707

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、查看接口返回

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

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文件上传功能的示例的文章就介绍到这了,更多相关laravel 阿里云oss文件上传内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

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

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部