layui combines SpringMVC to upload files and upload files with additional parameters

 

  In the process of using layui today, I encountered a module that uses it to upload files. I feel that the file uploading or the bootstrapfileinput plugin is easier to use, flexible and convenient, and the bootstrapfileinput usage reference: http://www.cnblogs.com/qlqwjy/p/8410413.html

 

  When using layui's file upload module, I wanted to carry additional parameters, and I fiddled here for a long time. . . Really pit. Here is a summary of the use of the layui file upload module.

1. The page prepares the modal box for file upload:

<!-- Several related modal boxes --> 
<!-- 1 S modal box for uploading pictures --> 
<% -- Hide the opened index -- %> 
< input type = "hidden" id = "hidden_picture_index" > 
< div class = "x-body" style = "display: none" id = "pictureModal" > 
    < div class = "layui-upload" > 
        <!-- Hide culture program number --> 
        < input type ="hidden" id ="hidden_trainSchemeId"> 
        <!-- Hide the operation of uploading files -->
        <input type="hidden" id="hidden_tmp_index">
        <button type="button" class="layui-btn" id="structurePicture"><!--动态赋值--></button>
        <!--预留一个预览的img标签-->
        <div id="imgDiv" style="display: none;margin-top: 10px;">
            <img id="imgPreview" width="400px" height="200px">
        </div>
        <div id ="promptDiv" style ="margin-top: 10px;display: none" > 
            < p >< font style ="font-size: 30px" > You have not uploaded the course relationship structure diagram, please upload the course relationship structure diagram first ! </ font ></ p > 
        </ div > 
    </ div > 
</ div > 
<!-- 1 E modal box for uploading images -->

 

 

2. JS for uploading files

layui.use(['upload','layer'], function () {
     var upload = layui.upload,layer = layui.layer;
     // normal image upload 
    var uploadInst = upload.render({
        elem: '#structurePicture', // Binding element 
        url: contextPath+'/TrainPicture/uploadTrainPicture.do', // Submitted url 
        auto: true , // Whether to upload automatically 
        accept:"images", // Specify to allow upload The file type of 
        multiple: false , // Support multiple file upload 
        acceptMime:"image/*", // Specify the file type to be filtered out when opening the file selection box 
/*         data:{
            trainningschemeid:  $("#hidden_trainSchemeId").val()
        },//Extra carried training scheme number */ 
        before: function (obj){
             this.data={"trainningschemeid": $("#hidden_trainSchemeId").val()}//carry extra data 
            // pre-read Local file example, ie8 not supported 
            obj.preview( function (index, file, result){
                $( '#imgPreview').attr('src', result); // Image link (base64) 
            });
             var index = layer.load(); // Open the load layer after uploading 
            $("#hidden_tmp_index" ).val(index); // Hide the index of the load layer into the page 
        },
        done: function (res, index, upload){ // Assume code=0 to represent successful upload 
            layer.close(layer.index); // It always gets the latest pop-up layer, and the value is dynamically incremented by the layer Calculated 
            if (res.msg=="Upload successful" ){
                 // Prompt that the upload is successful (change the content of the button to change the picture after closing) 
                layer.msg(res.msg, {icon: 1,time:2*1000 }, function () {
                    $( "#structurePicture").text("Replace the main course relationship structure diagram"); ​​// The button title is set to upload picture 
                    $("#promptDiv").css("display","none"); // Hide Prompt 
                    $("#imgDiv").css("display",""); // Display picture frame 
                });
            }

        }
    });
})




/* ************E Upload related operations of the training plan course structure diagram************** */

 

  The data attribute is used to carry additional parameters, but the parameters I bring are always "" (empty string). Later, I checked the online information and found that the second solution is to dynamically set the uploaded parameters in the function of the before file upload. For example the before function above. But sometimes the above data attribute can take effect, and sometimes it does not take effect. . . . . . Therefore, when carrying parameters, you need to refer to the above two methods to see which one takes effect.

 

3. Background for receiving files: (Java code)

    @RequestMapping("/uploadTrainPicture" )
     ​​public ResposeResult addTrainPicture(Trainpicture trainpicture, MultipartFile file){
         // 1. Save the picture to the local 
        String fileoriname= null ; // Original name 
        String filenowname= null ; // System generated name 
        if (file != null ){
            fileoriname = file.getOriginalFilename(); // Get the original name 
            filenowname = UUIDUtil.getUUID2()+ "."+FilenameUtils.getExtension(fileoriname); // UUID generates a new unique name + file extension 
        }

        try {
             FileHandleUtil.uploadSpringMVCFile(file, "trainPicture", filenowname);
        } catch (Exception e) {
            logger.error( "Error saving the picture of the culture program" ,e);
        }
        // 2. Call the service to save the database 
        trainpicture.setPictureoriname(fileoriname);
        trainpicture.setPicturenowname(filenowname);
        trainpicture.setUptime(new Date());
        ResposeResult respondResult = new ResposeResult();
        String result = null;
        try {
            result = trainPictureService.addTrainPicture(trainpicture)?"Upload succeeded":"Upload failed" ;
        } catch (SQLException e) {
            result = "Upload failed" ;
            logger.error( "Error saving culture program database" ,e);
        }
        resposeResult.setMsg(result);
        return resposeResult;
    }

 

  

  It is found that the principle of using bootstrapfileinput's multi-file upload plugin and layui's multi-file upload plugin is to upload one file at a time, and multiple files will be accessed multiple times, so java's MultipartFile does not need to be received in an array.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325358397&siteId=291194637