Multiple file upload and management based on AngularJS+Bootstrap

1. Preface
Recently, a project needs to achieve multi-file upload and management, and the project is developed based on bootstrap, so I checked some bootstrap file upload plugins, and finally found that bootstrap-fileinput is the most beautiful, this plugin can achieve multi-file upload and Management (plugins official address: http://plugins.krajee.com/file-input), the specific effects are as follows:

 (bootstrap-fileinput is not limited to image upload, it can also achieve file upload, but the thumbnail of the image is easy to identify, here is an example of image upload)

 The basic operation of the plugin can be referred to: http://www.jq22.com/jquery-info5231, this article is mainly for multi-file management

 

Before talking about how to use the plugin, let me tell you about the requirements for image management in the project:

1. You can upload multiple pictures

2. Only when the save button is clicked, the picture information is saved to the database

3. You can load the image information that has been saved to the database, and provide the delete function

 

Therefore, we can specify several file states:

Selected: has been placed in the plugin, but has not been uploaded to the server. As shown in the third picture above, there is an upload button below the picture.

Uploaded: It has been uploaded to the server, but the image information has not been saved to the database. As shown in the second picture above, there is a 100% progress bar below the picture.

 

Saved: Pictures whose picture information has been saved to the database, such as the first picture in the above picture, there is a delete button below these pictures. Clicking delete will delete the picture information from the database.

 

2. Introducing the necessary documents

<link href="<%=path%>/static/css/bootstrap-3.3.5/bootstrap.min.css" rel="stylesheet">
<link href="<%=path%>/static/css/bootstrap-3.3.5/fileinput.css" rel="stylesheet">

<script src="<%=path%>/static/js/jquery-1.11.3.js"></script>
<script src="<%=path%>/static/js/angularjs-1.3.9/angular.min.js"></script>
<script src="<%=path%>/static/js/bootstrap-3.3.5/bootstrap.min.js"></script>
<script src="<%=path%>/static/js/bootstrap-3.3.5/fileinput.js"></script>
<script src="<%=path%>/static/js/bootstrap-3.3.5/fileinput_locale_zh.js"></script>

 Among them, fileinput.js and fileinput_locale_zh.js are in the official package of the plugin, and angular.min.js and bootstrap.min.js will not be introduced.

 

3. Uploading multiple files

 

   First define the file control in the page:

<input id="input-images" type="file" multiple class="file-loading" accept="image/*">

 Then initialize the control, you can realize the multi-file upload of the component:

$("#input-images").fileinput({
    uploadUrl: "<%=path%>" + "/album/pictureFileUpload",
    allowedFileExtensions: ["jpg", "png", "gif"],
    resizePreference: 'height',
    maxFileCount: 10,
    language: 'zh',
    overwriteInitial: false,
    resizeImage: true,
});

 

 Of course, there are many properties during initialization, which will not be introduced here. The background code (using JFinal) is as follows:

 

public void pictureFileUpload() {
    UploadFile uploadFile = getFile();
    renderJson("{\"link\":" + "\"/fileinput/upload/" + uploadFile.getFileName()
            + "\"" + ",\"fileName\":\"" + uploadFile.getOriginalFileName()
            + "\"}");
}

 Note that Json must be returned at the end, even if an empty json string ("{}") is returned, the returned value is stored in the data.response in the foreground.

 

Fourth, the loading and deletion of existing files

Loading of existing files refers to displaying the existing files on the server in the control to realize file management and provide delete function, which mainly depends on the implementation of initialPreview.

  After obtaining the file name and file address on the server, use initialPreview and initialPreviewConfig to complete the loading and definition deletion operations:

var initPreview = new Array();//Display elements
     var initPreviewConfig = new Array();//Display settings
 
$.post(
    "<%=path%>" + "/album/getPicsByAlbum",
    {albumId: albumId},
    function(result) {
    for(var i=0;i<result.length;i++){
      var pictureFile = result[i];
        // used to display the uploaded image
            initPreview.push("<img src='" + pictureFile.PICADDRESS
                    + "' class='file-preview-image' alt='"+pictureFile.PICNAME+"' title='"+pictureFile.PICNAME+"'>");
            var config = new Object();
            config.caption = pictureFile.PICNAME;
            config.url="<%=path%>" + "/album/deletePicById";
            config.key=pictureFile.ID;
            initPreviewConfig.push(config);
    }
    initFileInput($scope);
        $("#input-images").fileinput('refresh', {
            initialPreview: initPreview,
            initialPreviewConfig: initPreviewConfig
        });
     }
);

 Click the delete icon, and the key value in the config will be passed to the background by default, and the deletePicById method can be defined in the background:

 

public void deletePicById() {
    String picId = getPara("key");
    service.deletePicById(Integer.valueOf(picId));
    renderJson("{}");
}

 

5. Answers to some questions

1. Why there are no attributes in the model, but related attributes can be displayed on the front end?

    The ActiveRecord function of JFinal is mainly used here. There is no need to define attributes and setter and getter methods. The attribute value is mapped in the attrs in the model. This attribute is the key-value pair of <key, value>, and the key value is the field name of the database. . Special reminder: Although the SQL statement is not case-sensitive, the field name is still case-sensitive. If the field name is capitalized, the key mapped to the model is capitalized. At the same time, the default id of JFinal as the primary key strategy cannot take effect. , need to be set in configPlugin, as follows: arp.addMapping("pictures", "ID", Picture.class), it is recommended that you name the database fields according to the Java naming convention.
files.sql

2. (Reference code) Why do you need to perform clear and destroy operations when initializing FileInput?

    Because the FileInput plugin will keep the file in the file field regardless of whether it is uploaded or not after selecting the file, so when you click again, the last selected file will be displayed, which does not meet the needs of multi-album management. I thought the clear operation could clear the file field. (The official document says so), but the actual operation found that it was not emptied, so clear was called, and then the file upload control was reinitialized after destory. (I'm not sure about this, I hope someone can give pointers)

3. How do you know which pictures need to be stored in the database when saving? What is this based on?

There is a selectedPics array on $scope, which is responsible for saving the final files that will be saved to the database. After the file is selected, the information of the selected file will be saved to this array, but the hasUpload attribute is false; after the file is uploaded, the corresponding hasUpload will be modified to true; after the upload is successful, the deletion (not yet saved to the database) will be executed from the Remove the corresponding element from the array. Some people will ask, after selecting a file, it will be deleted without uploading it. Wouldn’t the file information occupy the data position and cause the elements to be cluttered? In fact, no, in the fileuploaded event, which images have beenUploaded directly change the value of the corresponding position element of the array, and the array coordinates are obtained through the data-fileindex attribute value of the DIV where the image is located . It will replace the vacant value and will not change due to the deletion of the picture , which corresponds to the selectedPics array.
var idx = $("#"+previewId).attr("data-fileindex");
  For example, I have selected 3 pictures and they are not uploaded at this time. Their data-fileindexes are 0, 1, and 2. When I delete the middle picture and re-select a new picture, their data-fileindex will become 0. , 2, 3.
 

6. Code reference

The article is not well written, it is too sketchy, I have sorted out the source code for you, packaged it separately, and imported it directly with eclipse. The database script is files.sql (MySQL). Let's take a look at the code.

Finally, I only learned AngularJS, and the code is not proficient enough. If there is anything wrong, please leave a message.

Reference code download address:

http://download.csdn.net/detail/kevin19900306/9796449

 
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326779651&siteId=291194637