Seven cows---Summary of various problems with JavaScript SDK __java

Source: Internet
Author: User

Many users are using the seven-cow JS SDK (http://developer.qiniu.com/docs/v6/sdk/javascript-sdk.html
) in the process of encountering various problems.

Seven cows provide based on Plupload plug-in package upload demo http://jssdk.demo.qiniu.io/, if you do not need plupload plug-ins can refer to https://github.com/iwillwen/qiniu.js/ Tree/develop, here is mainly based on Plupload plug-in way to explain some of the problems encountered, through reference plupload documentation, can be modified to seven cattle demo to meet their business needs, Plupload Plug-ins use documents can refer to HTTP ://www.cnblogs.com/2050/p/3913184.html

1. About using our SDK to build test steps:
About the test set up using our SDK to upload a file to their own space, this is actually very simple, you can refer to our demo on it, but the demo download may need to modify some of the JSS,CSS reference, I am here directly to the modified package of the ZIP version of the demo:
Http://7xsjg3.com1.z0.glb.clouddn.com/JavaScriptLatest.zip
Download down to unpack only need to modify two places on it:
1. Modify the main.js inside the token part of the change into their own token on it, of course, here just to specify a specific token this method to set up the upload token, a total of 3 ways to set up token, you can refer to the 14th article in the blog.

2. Modify the index.html settings after the upload of the URL to display the link, which is modified to upload token in the corresponding space inside a domain name on it:

The screenshot of the link shown is that the link is uploaded successfully and can be accessed directly:

2. About the North China space Modification upload domain name:
If you need to upload to North China, you need to modify the domain name to upload, or it will be an error:

Modify the method is also relatively simple, only need to modify the Qiniu.js within the specified upload domain name, here to give the need to modify the place
You can change the following:

3. Regarding the uploading file naming question, may refer to:
Inside the Main.js, Unique_names is an argument under the Plupload plug-in, which generates a unique file name for each uploaded file when the value is true, which is automatically generated by the Plupload plug-in and, if set to false, The seven bulls here will be named after the original name of the upload.
1. Upload the SOCPE for the bucket form, the Unique_names parameter is set to False, after uploading the file key is the local filename abc.txt
2. Upload scope for bucket form, unique_names parameter set to True,plupload plugin will ignore local filename, and this name is not regular, upload file key is Plupload plug-in generated, Like Yc7DZRS1m73o.txt.
3. Upload scope for bucket:key form, upload file local name needs and scope key is consistent, otherwise will be the error key doesn ' t match with scope, note that this form is not set Unique_ Names is true because even if the upload file has a local name of Abc.txt, Plupload assigns another filename to the file.
4. The scope of the upload is bucket, but there is a set savekey in the token, this form Save_key should be set to true, and the local file name to upload also needs to be consistent with this savekey filename.
5. Through the JS front-end settings uploaded key, in the Main.js file set as follows:

' Key ': function (up, file) {
             var Key = "";
            Do something and key return
            key
            }

This default is logoff, you can configure this function if you want to personalize the key for each file on the front end.
This configuration must not take effect until unique_names:false, Save_key:false
When you cancel logoff, the priority is higher than: Getfilekey in the Qiniu.js file.

4. Set the custom preview style

This setting is in the Ui.js file, the default is
var ImageView = '? imageview2/1/w/100/h/100 '
can be modified to 
var ImageView = ' style character + style name '

5. About setting up Cancel upload can refer to:
Http://stackoverflow.com/questions/11014384/cancel-file-upload-listener
(File Plupload.dev.js 1950 line removefile:function (files) method)

6. Limit the types of uploaded files:
There are also two ways to do this:
1. By setting the Mimelimit field in token to qualify the type of upload file, the example
"image/*" means only uploading picture types;
"Image/jpeg;image/png" indicates that only images of JPG and PNG types are allowed to be uploaded;
"!application/json;text/plain" indicates that JSON text and plain text are prohibited from being uploaded. (Note the front exclamation)
2. Set the filter parameter in the Plupload directly in the JS front, as follows

You can use this parameter to restrict the type, size, and so on of the uploaded file, which is passed in as an object, which includes three properties:
        filters: {
            max_file_size: ' 100mb ',
            prevent_duplicates: True,
            //specify what files to browse
             for mime_types: [
            {title: "FLV Files", Extensions: "flv"}//qualified FLV suffix upload format Upload
            {title: "Video Files", Extensions: "Flv,mpg,mpeg,avi,wmv,mov,asf,rm,rmvb,mkv,m4v,mp4"},//Limited Flv,mpg,mpeg,avi , wmv,mov,asf,rm,rmvb,mkv,m4v,mp4 suffix format upload
            {title: "Image Files", Extensions: "Jpg,gif,png"},//limited jpg,gif,png suffix upload
            {title: "Zip Files", Extensions: "Zip"}//qualified zip suffix upload
             ]
        },

7. Set to select only one file at a time
The multi_selection parameters in the Plupload plug-in are controlled by the following

Set to select only one file
  Multi_selection:false at a time,

8. Set Cancel upload, suspend upload
Add two control buttons to index.html:

<a class= "btn btn-default btn-lg" id= "up_load"  href= "#" >
     <span> confirm upload </span>
</a >  
<a class= "btn btn-default btn-lg" id= "stop_load"  href= "#" >
     <span> suspend upload </span>

Then bind the two buttons inside the Main.js file and add the following code:

$ (' #up_load '). On (' click ', Function () {
   uploader.start ();
});
$ (' #stop_load '). On (' click ', Function () {
   uploader.stop ();
});

9. Cancel the Fragment upload
Will main.js inside Chunk_size: ' 4MB ' Set chunk_size: ' 0MB ', note that the fragment upload default can only be 4M, if you set a different slice of the size will occur upload failure.

10. Cancel Automatic upload
Change the Main.js file Auto_start parameter to Auto_start:false

11. About requesting token to occur across domains
Because it is recommended that users get token from the back-end SDK and then set the parameter uptoken_url: ' Get uptoken url ', there is a possibility of Cross-domain main.js, and then add Response.setheader on the server side (" Access-control-allow-origin "," * "); The corresponding header field can be.

12. Compress the pictures before uploading
Seven Cows JS SDK integrated Plupload plug-in itself with compression, that is, the picture file has not been uploaded before it is compressed, the specific settings only need to set the resize parameters in the Main.js, plus the following code can be:

You can use resize this parameter to compress the picture that will be uploaded, which is an object that contains 5 properties: Width
: Specifies the thickness of the compressed picture, or the width of the original picture if it is not set
: Specifies the height of the compressed picture, If you do not set this property, it defaults to the height of the original picture
crop: Whether or not to crop the picture
quality: The quality of the compressed picture, only valid for images in JPG format, default is 90. Quality can be used in conjunction with width and height, but can also be used alone, when used alone, compressed picture will not change the width, but due to the quality of the lower, so the volume will also become small
preserve_headers: Compressed After the image of the metadata, True is reserved, false is not persisted, default is true. Deleting a picture's metadata can reduce the size of the picture a little bit.

The configuration example of the resize parameter is as follows:

resize: {
  width:100,
  height:100,
  crop:true,
  Quality:60,
  Preserve_headers:false
}

13.Android WebView is not supported for JS SDK
In Android's own WebView, refer to the JS SDK demo (http://jssdk.demo.qiniu.io/):

public class Mainactivity extends activity {
    private webview webview;
    @Override
    protected void onCreate (Bundle savedinstancestate) {
        super.oncreate (savedinstancestate);
        Setcontentview (r.layout.activity_main);
        WebView = (webview) Findviewbyid (R.ID.WV);
        Webview.getsettings (). Setjavascriptenabled (true);
        Webview.setwebviewclient (New Webviewclient () {public
            Boolean shouldoverrideurlloading (webview view, String URL) {
                view.loadurl (URL); 
                return true;
            }
        });
        Webview.loadurl ("http://demos.qiniu.com/demo/simpleuploader/");
    }

But click the Select File button does not respond, this is webview to JS is not very support caused by the solution can be introduced to the Webview,jar package address as follows:
Https://github.com/delight-im/Android-AdvancedWebView/blob/master/JARs/Android-AdvancedWebView.jar
The methods used are written on the document, which is relatively simple:

Private Advancedwebview Mwebview;
    @Override
    protected void onCreate (Bundle savedinstancestate) {
        super.oncreate (savedinstancestate);
        Setcontentview (r.layout.activity_main);

        Mwebview = (Advancedwebview) Findviewbyid (R.id.webview);
        Mwebview.setlistener (this, this);
        Mwebview.loadurl ("http://jssdk.demo.qiniu.io/");
    }

14. About multiple button selection file demo
Many users are asked jssdk multiple file selection of the demo, in fact, more simple, just want to main.js file inside a few more new uploader objects can be, and then on the main page inside the corresponding upload button on it can be referred to this demo:http:// 115.231.183.78/javascript/views/index.html

Here's what you need to change in Main.js and indxe.html:
main.js inside more new several uploader objects

$ (function () {var uploader = Qiniu.uploader ({runtimes: ' Html5,flash,html4 ', Browse_button: ' Pickfile S ', container: ' Container ', drop_element: ' Container ', max_file_size: ' 100MB ', Flash_swf_u RL: ' js/plupload/moxie.swf ', Dragdrop:true, chunk_size: ' 4MB ', Uptoken: ' UM6IEH7MTWNWKGPJIMD08JDXL vviuelhi4mffoel:79apuiepttkidvgdhj9d9bfbnhe=:eyjzy29wzsi6imphdmfkzw1viiwizgvhzgxpbmuioje0ntk4odmymzv9cg== ',// Uptoken_url: $ (' #uptoken_url '). Val (),//It is of course advisable to obtain token domain: $ (' #domain ') via URL. val (), Auto_start:fal
                SE, init: {' filesadded ': function (up, files) {$ (' table '). Show ();
                $ (' #success '). Hide ();
                    Plupload.each (Files, function (file) {var progress = new Fileprogress (file, ' fsuploadprogress ');
                Progress.setstatus ("Wait ...");
            }); }, ' Beforeupload ': functioN (up, file) {var progress = new Fileprogress (file, ' fsuploadprogress ');
                var chunk_size = plupload.parsesize (this.getoption (' chunk_size '));
                if (Up.runtime = = ' HTML5 ' && chunk_size) {progress.setchunkprogess (chunk_size); }, ' Uploadprogress ': function (up, file) {var progress = new Fileprogress (f
                Ile, ' fsuploadprogress ');

                var chunk_size = plupload.parsesize (this.getoption (' chunk_size '));
            Progress.setprogress (file.percent + "%", file.speed, chunk_size);
            }, ' Uploadcomplete ': function () {$ (' #success '). Show (); }, ' fileuploaded ': function (up, file, info) {var progress = new Fileprogress (file, ' FSUPLOADP
                Rogress ');
            Progress.setcomplete (up, info); }, ' Error ': function (up, err, Errtip) {$ (' table'). Show ();
                var progress = new Fileprogress (err.file, ' fsuploadprogress ');
                Progress.seterror ();
            Progress.setstatus (Errtip);

    }
        }
    });
    Uploader.bind (' fileuploaded ', function () {console.log (' Hello man,a file is uploaded ');

    });
    $ (' #up_load '). On (' click ', Function () {Uploader.start ();
    });
    $ (' #stop_load '). On (' click ', Function () {uploader.stop ();

    });
    var Q2 = new Qiniujssdk (); var uploader2 = Q2.uploader ({runtimes: ' Html5,flash,html4 ', Browse_button: ' Pickfiles2 ', containe R: ' Container2 ', drop_element: ' Container2 ', max_file_size: ' 100MB ', Flash_swf_url: ' js/plupload/m Oxie.swf ', Dragdrop:true, chunk_size: ' 4MB ', Uptoken: ' um6ieh7mtwnwkgpjimd08jdxlvviuelhi4mffoel:79 apuiepttkidvgdhj9d9bfbnhe=:eyjzy29wzsi6imphdmfkzw1viiwizgvhzgxpbmuioje0ntk4odmymzv9cg== ',//Uptoken_url: $ (' #upt Oken_url ').Val (),//It is of course advisable to obtain token domain: $ (' #domain ') via URL. val (), Auto_start:false, init: {
                ' filesadded ': function (up, files) {$ (' table '). Show ();
                $ (' #success '). Hide ();
                    Plupload.each (Files, function (file) {var progress = new Fileprogress (file, ' fsuploadprogress ');
                Progress.setstatus ("Wait ...");
            }); }, ' Beforeupload ': function (up, file) {var progress = new Fileprogress (file, ' Fsuploadprogres
                S ');
                var chunk_size = plupload.parsesize (this.getoption (' chunk_size '));
                if (Up.runtime = = ' HTML5 ' && chunk_size) {progress.setchunkprogess (chunk_size); }, ' Uploadprogress ': function (up, file) {var progress = new Fileprogress (f
                Ile, ' fsuploadprogress '); var chunk_size = plupload.parsesize (this.geToption (' chunk_size '));
            Progress.setprogress (file.percent + "%", file.speed, chunk_size);
            }, ' Uploadcomplete ': function () {$ (' #success '). Show (); }, ' fileuploaded ': function (up, file, info) {var progress = new Fileprogress (file, ' FSUPLOADP
                Rogress ');
            Progress.setcomplete (up, info);
                }, ' Error ': function (up, err, Errtip) {$ (' table '). Show ();
                var progress = new Fileprogress (err.file, ' fsuploadprogress ');
                Progress.seterror ();
            Progress.setstatus (Errtip);

    }
        }
    });
    Uploader2.bind (' fileuploaded ', function () {console.log (' Hello man 2,a file is uploaded ');
    });
    $ (' #up_load2 '). On (' click ', Function () {Uploader2.start ();
    });
    $ (' #stop_load2 '). On (' click ', Function () {uploader2.stop (); });

the corresponding index.html file to add related buttons:

<div id= "Container" > <a class= "btn btn-default btn-lg" id= "Pickfiles" style= "width:160px" href= "#" > <i class= "Glyphicon glyphicon-plus" ></i> <span> Select File </span> </a&

        Gt <a class= "btn btn-default btn-lg" id= "Up_load" style= "width:160px" href= "#" > <span> confirm upload </span
            > </a> <a class= "btn btn-default btn-lg" id= "Stop_load" style= "width:160px" href= "#" > <span> pause upload </span> </a> </div> <div id= "Container2" > <a class= "btn btn-default btn-lg id=" Pickfiles2 "style=" width:160px "href=" # "> <i class=" Glyphicon glyph Icon-plus "></i> <span> Select File </span> </a> <a class=" Btn Btn-defaul  

        T btn-lg "id=" up_load2 "style=" width:160px "href=" # "> <span> confirm upload </span> </a> &lT;a class= "btn btn-default btn-lg" id= "stop_load2" style= "width:160px" href= "#" > <span> suspend upload </spa n> </a> </div> </div>

15. About uploading and setting token methods:
Upload is required to specify the upload token, because JS belongs to the Client SDK, does not contain the implementation of the build token, and will token put to the front-end generation will expose ak,sk very insecure, so it is necessary to obtain from the server or designated upload token, There are three ways to set up a total of main.js in this room:

Method 1
uptoken: ' <your upload token> ',//Uptoken is upload voucher, generated by other programs
2
uptoken_url: '/uptoken ',         // Ajax Request Uptoken url,** strongly recommends setting * * (server provided)
Method 3
uptoken_func:function (file) {    //When a uptoken is needed, the method is invoked
    / /do something return
    uptoken;
}

At initialization time, Uptoken, Uptoken_url, uptoken_func three parameters must have one set, and if multiple are provided, their priority is Uptoken > Uptoken_url > Uptoken_func, where Uptoken is the direct provision of upload vouchers, Uptoken_url is to provide access to the address of the upload certificate, if you need to customize the process of obtaining uptoken can be set Uptoken_func.

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.