Experience in the Use of Qiniu Picture Upload [JS]

Keywords: JSON SDK PHP html5

Last time I wrote Experience in the Use of Qiniu Picture Upload [PHP] The main point is how the back end generates Token for the front end

In fact, uploading pictures, the back-end is relatively simple, because the use of third-party is to reduce the pressure on the back-end, the front-end is relatively complex.

You may need to implement some interactive functions on the front end:

1. Users Click to select pictures

2. The user drags the picture directly into the div

3. Users will want to see the upload progress

4. Users want to see a preview

Before proceeding with the following steps, make sure that:

1. Backend can generate token normally

2. You downloaded the plupload.full.min.js and qiniu.min.js files

Start the first step

1. Introducing these two files into the page may need to follow the order, which I also forgot, you have to fumble for yourself.
2. Write a function that returns a parameter object.
var qiniu_upload_params = (params, init) => {
    var obj_init = {
        'FilesAdded': function(up, files) {
            plupload.each(files, function(file) {
                // When the file is added to the queue, it handles the related matters.
            });
        },
        'BeforeUpload': function(up, file) {
                // Processing related matters before uploading each file
        },
        'UploadProgress': function(up, file) {
                // When uploading each file, deal with related matters
        },
        'FileUploaded': function(up, file, info) {
                // After each file has been uploaded successfully, deal with related matters
                // Among them, info is the json returned by the server after the file upload is successful, in the form of:
                // {
                //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
                //    "key": "gogopher.jpg"
                //  }
                // View Simple Feedback
                // var domain = up.getOption('domain');
                // var res = parseJSON(info);
                // Var sourceLink = domain +"/"+res.key; Gets the Url of the uploaded file
        },
        'Error': function(up, err, errTip) {
                //Handle related issues when uploading errors
        },
        'UploadComplete': function() {
                //After the queue file has been processed, do something about it.
        },
        'Key': function(up, file) {
            // If you want to personalize the key of each file at the front end, you can configure the function
            // This configuration must take effect only when unique_names: false, save_key: false
            // do something with key here
            var type = file.type;
            type = type.split("/");
            return 'image-tmp/'+ file.id+ "."+ type[1];
        }
    }
    Object.assign(obj_init, init);
    var obj = {
      runtimes: 'html5,flash,html4',      // Upload mode, degraded in turn
      browse_button: 'pickfiles',         // Upload Selected Click-on Button, Necessary
      // At initialization, one of the three parameters uptoken, uptoken_url, uptoken_func must be set
      // If more than one is provided, the priority is uptoken > uptoken_url > uptoken_func
      // Upoken is to provide the upload credentials directly, uptoken_url is to provide the address to obtain the upload credentials, if you need to customize the process of obtaining uptoken, you can set up uptoken_func.
      // Uptoken:'< Your upload token >', // uptoken is an upload credential generated by other programs
      uptoken_url: '*********',         // Ajax requests uptoken's Url and strongly recommends settings (servers provide)
      // uptoken_func: function(){// This method is called when uptoken is needed
      //    // do something
      //    return uptoken;
      // },
      get_new_uptoken: false,             // Whether to retrieve new uptoken every time you upload a file
      // downtoken_url: '/downtoken',
      // Ajax requests downToken's Url, which is used in private space. JS-SDK will send the key and domain of the POST file to the address. The JSON returned by the server must contain the URL field, and the URL value is the download address of the file.
      // unique_names: true, // default false, key is the file name. If this option is turned on, JS-SDK automatically generates key (file name) for each file.
      // save_key: true, // default false. If sava_key is specified in the upload policy for generating uptoken on the server side, the SDK will not process the key at the front end.
      domain: '********',     // bucket domain name, used when downloading resources, necessary
      container: 'container',             // Upload area DOM ID, default is the parent element of browser_button
      max_file_size: '100mb',             // Maximum File Volume Limitation
      flash_swf_url: 'path/of/plupload/Moxie.swf',  //Introducing flash, relative path
      max_retries: 3,                     // Maximum number of retries for upload failures
      dragdrop: true,                     // Open draggable upload
      drop_element: 'container',          // Drag the ID of the element in the upload area. Drag a file or folder to trigger the upload.
      chunk_size: '4mb',                  // When uploading blocks, the volume of each block
      auto_start: true,                   // Select the file and upload it automatically. If you close it, you need to bind the event yourself to trigger the upload.
      //x_vars : {
      //    View custom variables
      //    'time' : function(up,file) {
      //        var time = (new Date()).getTime();
                // do something with 'time'
      //        return time;
      //    },
      //    'size' : function(up,file) {
      //        var size = file.size;
                // do something with 'size'
      //        return size;
      //    }
      //},
      init: obj_init
    }
    Object.assign(obj, params);
    return obj;
}
Once this parameter is done, it will be very simple to use. (Notes are very clear, if you don't understand, you can leave a message to me.)
You can use the function you just wrote as follows, where image_show div is the parent container, image_show is the word container, and it is also used as a preview image.
var imageupload = Qiniu.uploader(qiniu_upload_params({
        container: "image_showdiv",
        browse_button: "image_show",
        drop_element: "image_show",
    },{
        FileUploaded: function(up, file, info){
            var rs = JSON.parse(info);
            $("#image_show").css("backgroundImage", "url('*********"+ rs.key+ "')");
            $("#sysfrontendhomebanner-image").val(rs.key);
        }
    }));
It's just a very basic use.
After uploading the picture successfully, the client has to download it again to see the picture. In fact, after the client has selected the picture, he can immediately pick it up and display it in the position you want to display.
Also, in order to prevent users from repeatedly uploading, it is better to wait a few seconds before uploading to Qiniu. If there are fewer pictures, upload pictures when submitting forms.
There is no restriction on the type of resources users can upload, that is, anything can be uploaded.
Without limiting the number of user uploads, users may upload a lot at a time.
You can fumble about these things... I think writing code is like doing experiments.

Posted by stuckwithcode on Sat, 15 Jun 2019 11:56:27 -0700