Spring Boot Membership Management System-Processing File Upload

Posted by ldd76 on Thu, 16 May 2019 14:00:11 +0200

Reminder
Spring Boot membership management system needs to involve Spring framework, Spring MVC framework, Hibernate framework, thymeleaf template engine. So, you can learn these knowledge. Of course, it's okay to use it directly, but it may be difficult to use it when it comes to some exceptions and principles.

1. Front end part

In the front-end part, addMember.html submits members'information through the form form form, which includes the image upload function (file upload operation is involved here). The form part code is as follows:

<form th:action="@{/admin/addMember}" method="post" enctype="multipart/form-data" id="addMember">
                            <div class="file-field input-field">
                                <div class="btn">
                                    <span>Select the avatar file</span>
                                    <input id="file" type="file" name="iconPath" multiple="" placeholder="Select file" accept="image/*" onchange="changeToop()">
                                </div>
                                <div class="file-path-wrapper">
                                    <!--<input class="file-path validate" type="text" placeholder="Upload one or more files">-->
                                    <img id="myimg" src="assets/iconPath/common.jpg" class="img-responsive img-thumbnail" style="width: 20%;height: 20%" />
                                </div>
                                <!--Preview of uploading avatar files-->
                                <script>
                                    function Id(id){
                                        return document.getElementById(id);
                                    }
                                    function changeToop(){
                                        var file = Id("file");
                                        if(file.value===''){
                                            //Setting default images
                                            Id("myimg").src='assets/iconPath/common.jpg';
                                        }else{
                                            preImg("file","myimg");
                                        }
                                    }
                                    //Get the url Important of the input[file] image
                                    function getFileUrl(fileId) {
                                        var url;
                                        var file = Id(fileId);
                                        var agent = navigator.userAgent;
                                        if (agent.indexOf("MSIE")>=1) {
                                            url = file.value;
                                        } else if(agent.indexOf("Firefox")>0) {
                                            url = window.URL.createObjectURL(file.files.item(0));
                                        } else if(agent.indexOf("Chrome")>0) {
                                            url = window.URL.createObjectURL(file.files.item(0));
                                        }
                                        return url;
                                    }
                                    //Preview after reading the picture
                                    function preImg(fileId,imgId) {
                                        var imgPre =Id(imgId);
                                        imgPre.src = getFileUrl(fileId);
                                    }
                                </script>
                            </div>
                            
                           .......
                            
                        </form>

Here's a note: because file upload is involved, enctype="multipart/form-data" needs to be added to form, and the name attribute in input corresponds to the incoming parameter name of the Controller mapping method in the back end.

2. Backend Code Implementation

In the back end, the Spring MVC framework can process files and then we can receive them by passing in parameters.

2.1 Controller handles incoming files

The code is as follows:

@PostMapping("/addMember")
    public String addMember(Member member, String gradeName, MultipartFile icon, Map<String, Object> model) {
        //Processing uploaded files
        try {
            if (icon == null)//First, determine that the uploaded file is not null
                return "error";
            if (icon.getOriginalFilename().equals("")) //If the original name of the uploaded file is an empty string, the default image is proved to be used.
                member.setIconPath("/assets/icon/common.jpg"); //Set to our default image path
            else
                //Here we use our own file upload tool class to process the uploaded MultipartFile, and the file name is set to the string generated by UUID.
                member.setIconPath(FileUploadUtil.upload(icon, "/assets/icon/", UUIDRandomUtil.get32UUID()));
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        
        .......
        
        return "addMemberSuccess";
    }
2.2 FileUploadUtil tool class saves files

After the Controller's MultipleFile file is imported, it needs to be further converted to FIle and saved to disk. So I process it separately and hand the Controller's imported file to the FileUploadUtil tool class for processing. The specific code is as follows:

public class FileUploadUtil {

    /**
     * Upload files
     * @param multipartFile multipartFile
     * @param prefixPath Prefix paths, as opposed to paths in the entire project, do not need to be preceded by "/"
     * @param fileName Uploaded file name
     * @return Final Relative Path + File Name after Upload
     * @throws Exception Possible null pointer exceptions and IO exceptions
     */
    public static String upload(MultipartFile multipartFile, String prefixPath, String fileName) throws Exception {
        //Find the absolute path to upload
        String uploadPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() +"/static"+ prefixPath;
        File file = new File(uploadPath);
        if (!file.exists())
            if (file.mkdirs())
                System.out.println("Successful directory creation");
        //Get the uploaded suffix name
        String suffixName = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        //New finalized document
        file = new File(uploadPath+fileName+suffixName);
        multipartFile.transferTo(file);
        return prefixPath+fileName+suffixName;
    }

}

ClassUtils in the above is a tool class provided by Spring, and the call method getDefaultClassLoader().getResource("").getPath() is the path under the current project classpath.

Above is part of the system about file upload, the source code of the system upload. GitHub and CSDN resources

Topics: Java Spring Hibernate Thymeleaf Firefox