The sample code for uploading images to qiniu cloud by the front-end js in Laravel,
The following Laravel uses a browser to upload images to qiniu cloud. Here are some simple process examples.
1. first introduce the corresponding js file. below is the StaticfileCDN introduced through CDN. Of course, there are many other methods to download the SDK, such as bower, git, and official website.
Qiniu js is encapsulated based on the Plupload plug-in, so you need to download Plupload. We recommend that you use 2.1.1 ~ 2.1.9.
<script src="https://cdn.staticfile.org/jquery/2.2.1/jquery.min.js"></script><script src="https://cdn.staticfile.org/plupload/2.1.9/moxie.js"></script><script src="https://cdn.staticfile.org/plupload/2.1.9/plupload.dev.js"></script><script src="https://cdn.staticfile.org/qiniu-js-sdk/1.0.14-beta/qiniu.min.js"></script>
2. Create a select file button
<Div id = "container"> <a class = "btn-default btn-lg" id = "pickfiles" href = "#" rel = "external nofollow"> <span> select a file </span> </a> </div>
3. initialize uploader
(Please ensure that plupload has been introduced to the page during initialization). Here we need an uptoken upload credential, which must be generated by the php backend. Next we will explain how to get the token.
Function uploaderReady (token) {console. log (token); var uploader = Qiniu. uploader ({runtimes: 'html5, flash, html4', // upload mode, degradation browse_button: 'pickfiles' in turn, // upload button ID uptoken: token, // uptoken is the upload credential generated by other programs. // uptoken_url: '/uptoken', // Url of the Ajax request uptoken. We strongly recommend that you set it (provided by the server) // uptoken_func: function () {// when you need to obtain the uptoken, this method will be called // do something // return uptoken; //}, get_new_uptoken: false, // set the object to be uploaded Whether to obtain the new uptoken unique_names every time: true, // The default value is false, and the key is the file name. If this option is enabled, the JS-SDK automatically generates a key (File Name) // save_key: true for each file, // The default is false. If the sava_key is specified in the upload policy for the uptoken generated by the server, the SDK is enabled and does not process the key at the front end. domain: 'http: // ovngj7u9c.bkt.clouddn.com ', // bucket domain name, required for resource download. container: 'Container' is required. // upload the dom id of the region. The default value is max_file_size: '100mb', the parent element of browser_button. // The maximum file size is flash_swf_url: 'path/of/plupload/Moxie.swf ', // introduce flash, relative path max_retries: 1, // maximum number of retries of upload failure dragdrop: true, // enables drag upload drop_element: 'Container', // drag the ID of the element in the upload area. After a file or folder is dragged, The chunk_size: '4mb 'upload can be triggered. // the size of each chunk_size: '4mb' in the multipart upload mode is auto_start: true, // select a file and upload it automatically. If the file is disabled, bind the event to trigger the upload init: {'filesadded': function (up, files) {plupload. each (files, function (file) {// After the file is added to the queue, process related tasks}) ;}, 'beforeupload': function (up, file) {// process related tasks before each file is uploaded}, 'uploadprogress': function (up, file) {// process related tasks when each file is uploaded }, 'fileuploaded': function (up, file, info) {// after each file is uploaded successfully, process the related information. // info indicates the json returned by the server after the file is uploaded successfully, format: // {// "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98", // "key ": "gogopher.jpg" //} // obtain the url path and input it to the backend and save it to the database var domain = up. getOption ('domain '); var url = JSON. parse (info); var sourceLink = domain + "/" + url. key; $. ajax ({url: '/image', type: 'post', dataType: 'json', data: {' _ token': "{csrf_token ()}}", "url": sourceLink},}) ;}, 'error': function (up, err, errTip) {console. log (errTip) ;}, 'uploadcomplete': function () {// process related tasks after the queue file is processed}, 'key': function (up, file) {// If You Want to personalize the key of each file on the front end, you can configure this function. // The configuration must be in unique_names: false, save_key: var key = ""; // do something with key here return key }}});}
4. the backend obtains the upload token.
First, install packagist of qiniu at the github address.
composer require "overtrue/laravel-filesystem-qiniu" -vvv
Add in app/config. php
'providers' => [ // Other service providers... Overtrue\LaravelFilesystem\Qiniu\QiniuStorageServiceProvider::class,],
Configure your qiniu information in config/filesystems. php.
<?phpreturn [ //... 'qiniu' => [ 'driver' => 'qiniu', 'access_key' => env('QINIU_ACCESS_KEY', 'xxxxxxxxxxxxxxxx'), 'secret_key' => env('QINIU_SECRET_KEY', 'xxxxxxxxxxxxxxxx'), 'bucket' => env('QINIU_BUCKET', 'test'), 'domain' => env('QINIU_DOMAIN', 'xxx.clouddn.com'), // or host: https://xxxx.clouddn.com ], //...];
Then write the code to get the token in your controller store method, so that the front-end can get the token Using ajax requests.
public function store(){ $disk = Storage::disk('qiniu'); $token = $disk->getUploadToken(); return response()->json(['uptoken'=>$token]);}
5. With the token, we will continue to improve the front-end code.
To understand how to write an ajax request to store, you can also set the request address in the uptoken_url attribute of uploader.
Function getTokenMessage () {$. ajax ({url: 'Your controller address', type: 'post', data: {'_ token': "{csrf_token ()}"}, dataType: 'json', success: function (data) {var obj = data; // after the request is successful, call the prepared uploaderReady method and pass the token to uploaderReady (obj. uptoken) ;}}) ;}// request $ (document) during page initialization ). ready (function () {getTokenMessage ();});
This is almost the case. For more operations, refer to the official js document of qiniu cloud.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.