1. ホーム
  2. Web プログラミング
  3. PHP プログラミング
  4. phpの例

AliCloudのossファイルアップロード機能をlaravelで実装した例

2022-01-15 21:12:06

1. ルートの定義

// Aliyun file storage
Route::group(['prefix'=>'aliyun'], function(){
    Route::get('sign', 'AliyunController@sign');
}); 

2. コントローラ層の記述

/**
     * Return OSS signature verification
     * @return JSON signature information
     */
    public function sign(Request $request)
    {
        //initialize the necessary request data
        $id = 'xxx'; //AccessKeyId
        $key = 'xxx'; //AccessKeySecret
        $host = '//xxx.oss-cn-shenzhen.aliyuncs.com'; //OSS repository address
        $cdn_host = "//img.xxx.com"; //real access address
        $dir = 'test/'; //upload directory setting
        $callbackUrl = url('upload/callback'); //address of the upload callback

        //upload callback parameters, callbackUrl address, callbackBody callback received parameters, callbackBodyType callback function called via POST, so set this header
        $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); //convert to json format
        $base64_callback_body = base64_encode($callback_string); // information about the callback function parameters to be returned

        //set the expiration time
        $now = time();
        
        $expire = 60 * 60 * 2; //Set the policy timeout time to 2 hours. That is, this policy will not be accessible after this valid time, you can set it according to your own token expiration time here
        $end = $now + $expire;
        $expiration = $this->gmt_iso8601($end); //convert the time format


        //handle upload constraints
        //maximum file size. Users can set their own
        $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
        $conditions[] = $condition; //set file size
        //indicates that the data uploaded by the user must start with $dir, otherwise the upload will fail, this step is not necessary, just for security reasons, to prevent users from uploading to other people's directories via policy
        $start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
        $conditions[] = $start; // must start with the set directory, to prevent upload errors
        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy); //the upload restriction parameters to return

        //signature information
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true)); //signature information to be returned

        //set the return message
        $response = array(
            'accessid' => $id, //accessid
            'host' => $host, //upload address
            'cdn_host' => $cdn_host, //real access address
            'policy' => $base64_policy, //upload file limit
            'signature' => $signature, //signature information
            'expire' => $end, //expiration time
            'callback' => $base64_callback_body, //upload callback parameters
            'dir' => $dir // directory to upload to
        );
        return response()-> json([
            'code' => 0,
            'msg' => 'success',
            'data' => $response
        ]);
    }

    //formatted time, formatted as 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の使用です

<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" >upload</a>

        </div>
    </div>
</template>



<script>
export default {
    data(){
        return {

        }
    },
    mounted() {
    
        this.getOssToken();
    },
    methods: {
        //Get the upload pass
        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("Please select the file");
            }

            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();

            // Note the case of the key added by append in formData
            formData.append('key', _self.aliyunOssToken.dir + filename); //file path stored in oss
            formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId
            formData.append('policy', _self.aliyunOssToken.policy); //policy
            formData.append('Signature', _self.aliyunOssToken.signature); //signature
            formData.append("file", $("#file")[0].files[0]);
            formData.append('success_action_status', 200); //action code returned after success


            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. アップロードボタンをクリックすると、ブラウザのコンソールに画像を見るためのリンクが出力されます

これは、アリクラウドOSSファイルアップロード機能の例のLaravelの実装について、この記事の終わりです、より関連するLaravelアリクラウドOSSファイルアップロードの内容は、スクリプト家の以前の記事を検索するか、次の関連記事を閲覧し続けるあなたは将来的に多くのスクリプト家をサポートして願っています!。