Laravel frame in JavaScript upload images to seven Qiniu case detailed

Source: Internet
Author: User
The following Laravel use browser-side upload image to seven cow cloud, below just do some simple process examples.

1. First introduce the corresponding JS file, the following is introduced through the CDN Staticfilecdn, of course, there are many other ways to download, Bower,git, the official website of the SDK
Seven Bull JS based on Plupload plug-in package, so need to download plupload, recommended to 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 button to select a file


  <p id= "Container" >    <a class= "btn btn-default btn-lg" id= "Pickfiles" href= "#" rel= "external nofollow" >< C2/><span> Select File </span>    </a>  </p>

3. Initialize Uploader

(Make sure that the page has been introduced plupload when the initialization is performed), here we need a Uptoken upload credential, which needs to be provided by PHP backend generation. How can we get tokens next?


  function Uploaderready (token) {console.log (token); var uploader = Qiniu.uploader ({runtimes: ' html5,flash,html4 ',//upload mode, degenerate Browse_button in turn: ' Pickfiles ',//upload     Button ID Uptoken:token,//Uptoken is upload voucher, generated by other program//uptoken_url: '/uptoken ',//Ajax request Uptoken URL, strongly recommended setting (server side provided)     Uptoken_func:function () {///the method will be called when Uptoken is required////do something//return uptoken; }, Get_new_uptoken:false,//sets whether to retrieve the new Uptoken unique_names:true each time the file is uploaded,//The default false,key is the file name. If this option is turned on, JS-SDK will automatically generate a key (filename)//save_key:true for each file,//default false. If Sava_key is specified in the upload policy of the server generation Uptoken, the SDK will not process the key in the frontend domain: ' http://ovngj7u9c.bkt.clouddn.com ',//buckets, Download resources, required container: ' container ',//upload area Dom ID, default is Browser_button parent element max_file_size: ' 100MB ',//MAX      File volume limit flash_swf_url: ' path/of/plupload/moxie.swf ',//flash introduced, relative path max_retries:1,//upload failed maximum retry attempts Dragdrop:true,//open can drag upload drop_element: ' container ',//Drag the ID of the upload AREA element, drag the file or folder can trigger upload chunk_size: ' 4MB ',//block upload, the volume of each piece          Auto_start:true,//Select file after automatic upload, if close need to self-bind event trigger upload init: {' filesadded ': function (up, files) {        Plupload.each (Files, function (file) {///file added to queue, processing related things}); }, ' Beforeupload ': function (up, file) {////each file before uploading, handling related things}, ' uploadprogress ': function (U P, file) {//each file is uploaded, processing related things}, ' fileuploaded ': function (up, file, info) {///each file is uploaded successfully,          Handle related things//where info is the file upload after successful, the server returns JSON, form such as://{//"hash": "Fh8xvqod2mq1mocfi4s4kprl6d98",            "Key": "Gogopher.jpg"//}//Gets the URL path to the backend to save 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 () {///queue file processing completed, processing related things}, ' Key ': function (up, file) {          If you want to personalize the key of each file on the front end, you can configure the function//the configuration must be in Unique_names:false,save_key:false when the var key = "";  Do something with key here Return key}}); }

4. Back end Get upload voucher token

First, we'll install a seven-ox packagist,github address.


Composer require "Overtrue/laravel-filesystem-qiniu"-VVV

Add inside the app/config.php


' Providers ' = [  //Other service providers ...  Overtrue\laravelfilesystem\qiniu\qiniustorageserviceprovider::class,],

Then configure your seven KN 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 token in your controller store method, a good way for the front end to get the AJAX request


Public function Store () {  $disk = Storage::d ISK (' Qiniu ');  $token = $disk->getuploadtoken ();    return response ()->json ([' uptoken ' = $token]);}

5. With token we continue to refine the front-end code

To understand that we write an AJAX request store, of course you can also set the request address in the Uptoken_url property 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 Uploaderready method just written, and pass the token into the past Uploaderready (Obj.uptoken); }  });} Ask for $ (document) when the page is initialized. Ready (function () {gettokenmessage ();}); 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.