Processing file upload function of Spring Boot member management system, spring Member Management System

Source: Internet
Author: User

Processing file upload function of Spring Boot member management system, spring Member Management System

Tip

The Spring Boot member management system involves the Spring framework, SpringMVC framework, Hibernate framework, and thymeleaf template engine. Therefore, you can learn this knowledge. Of course, it is okay to get started directly. However, if exceptions and principles are involved, it may be difficult.

1. Front-end

The front-end uploaddmember.html submits member information through the form, which includes the image upload function (file upload operations are involved here). Some code of the form 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 an 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"> -->  </div> <! -- Upload and preview an avatar file --> <script> function Id (id) {return document. getElementById (id);} function changeToop () {var file = Id ("file"); if (file. value = '') {// sets the default image Id (" myimg "). src = 'Assets/iconPath/common.jpg ';} else {preImg ("file", "myimg ");}} // obtain the url Important 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 function preImg (fileId, imgId) {var imuple = Id (imgId); imuple. src = getFileUrl (fileId) ;}</script> </div> ....... </form>

Note: Because file upload is involved, you must addenctype="multipart/form-data"In addition, the name attribute in input corresponds to the input parameter names of the Controller ing method in the backend.

2. backend code implementation

The SpringMVC framework can process files in the backend, and then we can receive files by passing in parameters.

2.1 The Controller processes incoming files.

The Code is as follows:

@ PostMapping ("/addMember") public String addMember (Member member, String gradeName, MultipartFile icon, Map <String, Object> model) {// process the uploaded file try {if (icon = null) // first, judge whether the uploaded file is not null return "error"; if (icon. getOriginalFilename (). equals ("") // if the original name of the uploaded file is a null string, the default image member is used. setIconPath ("/assets/icon/common.jpg"); // set it to our default image path else // you can use your own file upload tool class to process uploaded multipartfiles, the file name is set to the member string generated by UUID. setIconPath (FileUploadUtil. upload (icon, "/assets/icon/", UUIDRandomUtil. get32UUID ();} catch (Exception e) {e. printStackTrace (); return "error ";}....... return "addMemberSuccess ";}

2.2 FileUploadUtil tool class save files

After the Controller's MultipartFile FIle is passed in, it needs to be further converted to a FIle and saved to the disk. So I separate the FIle and hand over the Controller's incoming FIle to the FileUploadUtil tool class for processing. The specific code is as follows:

Public class FileUploadUtil {/*** Upload File * @ param multipartFile * @ param prefixPath prefix path, relative to the path in the entire project, you do not need to add "/" * @ param fileName to the top of the path. the uploaded file name * @ return is the final relative path after the upload + file name * @ throws Exception may cause NULL pointer exceptions and IO exceptions * /public static String upload (MultipartFile multipartFile, string prefixPath, String fileName) throws Exception {// obtain the absolute upload path String uploadPath = ClassUtils. getdefaclasclassloader (). getRes Ource (""). getPath () + "/static" + prefixPath; File file = new File (uploadPath); if (! File. exists () if (file. mkdirs () System. out. println ("successfully created directory"); // obtain the uploaded suffix String suffixName = multipartFile. getOriginalFilename (). substring (multipartFile. getOriginalFilename (). lastIndexOf (". "); // create the final file File = new file (uploadPath + fileName + suffixName); multipartFile. transferTo (file); return prefixPath + fileName + suffixName ;}}

The ClassUtils above is a tool class provided by Spring, and the call MethodgetDefaultClassLoader().getResource("").getPath()Is to obtain the path under the current project classpath.

The above is part of the file upload in the system. The source code of the system is uploaded to GitHub and the source code is downloaded.

Summary

The above section describes the File Upload processing function of the Spring Boot member management system. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.