springboot Computer Shop Project 5. Upload user profile

5. Upload your Avatar

1. Upload Avatar - persistence layer

1.1 sql statement planning

update t_user set avatar = ?,modified_user = ? ,modified_time = ? where uid = ?

1.2 Design interfaces and abstract methods

UserMapper interface to define an abstract method for modifying user avatars

/**
 *
 * @param uid
 * @param avatar
 * @param modifiedUser
 * @param modifiedTime
 * @return
 */
Integer updateAvatarById(@Param("uid") Integer uid,
                         @Param("avatar") String avatar,
                         @Param("modifiedUser") String modifiedUser,
                         @Param("modifiedTime") String modifiedTime);

Mapping of 1.3 Interface

UserMapper. Writing mapped sql statements in XML files

<update id="updateAvatarById">
    update
   		t_user
    SET
   		avator = #{avatro},
    	modified_user = #{modifiedUser},
    	modified_time = #{modifiedTime}
    WHERE
    	uid = #{uid}
</update>

Write test methods in test classes

@Test
public void updateAvatarById(){
    userMapper.updateAvatarById(29,"/load/picture.png","Administrators",new Date());
}

2. Upload avatar-business layer

2.1 Planning Exceptions

1. User data does not exist, corresponding user data cannot be found

2. Unknown exception when updating

The above exceptions do not need to be redeveloped

2.2 Design interfaces and abstract methods

/**
     * Modify user profile
     * @param uid
     * @param avatat
     * @param modifiedUser
     */
void changeAvatar(Integer uid,String avatat,String modifiedUser);

2.3 Implementing abstract methods

@Override
public void changeAvatar(Integer uid, String avatat, String username) {
    //Query whether the current user exists
    User result = userMapper.findUserById(uid);
    if (result == null){
        throw new UserNotFoundException("User data does not exist");
    }
    Integer rows = userMapper.updateAvatarById(uid, avatat, username, new Date());
    if (rows != 1){
        throw new UpdateException("Unknown exception when updating Avatar");
    }
}

Write test methods in test classes

@Test
public void changeAvatar(){
    userService.changeAvatar(29,"/update/123.png","Zhang San");
}

3. Upload avatar-control layer

3.1 Planning Exceptions

FileUploadException Generic refers to exception (parent) inheritance of file uploads RunntimeException
 The parent class is: FileUploadException
	FileEmptyException Exception with empty file
	FileSizeException File size exceeds limit
	FileTypeException File type exception
	FileUploadIOException File read-write exception

Five construction methods are declared, then the related parent class is inherited

3.2 Handling Exceptions

Write and unify in base class BaseController class

else if (e instanceof FileEmptyException) {
    result.setState(6000);
} else if (e instanceof FileSizeException) {
    result.setState(6001);
} else if (e instanceof FileTypeException) {
    result.setState(6002);
} else if (e instanceof FileStateException) {
    result.setState(6003);
} else if (e instanceof FileUploadException) {
    result.setState(6004);
}

Add a new exception handling as its parameter to the parameter list of the Unified Exception Handling Method

@ExceptionHandler({ServiceException.class,FileUploadException.class})

3.3 Design Request

/user/change_avatar
POST(get Request Submission Data 2 kb)
HttpSession session,MutipartFile file
JsonResult<String>

3.4 Upload avatar function

/**
     * MultipartFile Interface is an interface provided by SpringMvc, which is wrapped for us
     * Get data of file type (any type of file can be received), Springboot integrates again
     * SpringMVC,Simply declare a parameter of type MultipartFile on the method parameter that handles the request.
     * springboot then automatically assigns the file data passed to the service to this parameter
     *
     * @param session
     * @param file
     * @return
     */
@RequestMapping("change_avatar")
public JsonResult<String> changeAvatar(HttpSession session, @RequestParam("file") MultipartFile file) {
    //Determine whether the file type is null
    if (file.isEmpty()) {
        throw new FileEmptyException("File is empty");
    }
    //Determine File Size
    if (file.getSize() > AVATAR_MAX_SIZE) {
        throw new FileSizeException("File size exceeds limit");
    }
    //Determine File Type
    String contextType = file.getContentType();
    //Determine File Type
    if (AVATAR_TYPE.contains(contextType)) {
        throw new FileTypeException("File type not supported");
    }
    //Get absolute project path
    String parent = session.getServletContext().getRealPath("upload");
    System.out.println(parent);//Will be deleted
    //File object points to this path, does File exist
    File dir = new File(parent);
    if (!dir.exists()) {//Detect directory existence
        dir.mkdir();//Create a new directory if the current path does not exist
    }
    //Get the file name and use the UUID tool later to generate a new string for the file name
    String originalFilename = file.getOriginalFilename();
    System.out.println("OriginalFilename" + originalFilename);//Delete
    int index = originalFilename.lastIndexOf(".");
    String suffix = originalFilename.substring(index);
    String filename = UUID.randomUUID().toString().toUpperCase() + suffix;
    File dest = new File(dir, filename);//Create a new file in the dir directory. Empty!!
    //Write data from parameter file to this empty file
    try {
        file.transferTo(dest);//Write data from file to dest
    } catch (FileStateException e) {
        throw new FileStateException("File status exception");
    } catch (IOException e) {
        throw new FileUploadException("File read-write exception");
    }

    Integer uid = getUidFromSession(session);
    String username = getUsernameFormSession(session);
    //Path to return avatar/upload/test.png
    String avatar = "/upload/" + filename;
    iUserService.changeAvatar(uid,avatar,username);
    //Return the path of the user's avatar to the front-end page for future use in Avatar display
    return new JsonResult<>(OK,avatar);
}

4. Upload avatar-front page

Write code to upload your avatar on the upload page

Description: If you upload files directly using the form, you need to add an attribute to the form display: enctype="multipart/form-data".

The data structure of the target file will not be modified in the upload.

<form action="/users/change_avatar"
     method="post"
     enctype="multipart/form-data"
</form>

5 Solve bug s

5.1 Change the default size limit

Springmvc defaults to 1 MB file for upload, manually modifying the size of SpringMVC default upload file

Mode 1: Configure directly in the configuration file, simplest

spring.servlet.multipart.maxFileSize=10MB
spring.servlet.multipart.maxRequestSize=10MB

Mode 2: You need to set the file upload size limit in the form of java code. Configuration in the main class defines a method that must be decorated with the @Bean modifier. Modify the class by adding the @Configration annotation before it. Return value must be MutilpartConfigElement

@Configuration//Represents a configuration class
@SpringBootApplication
@MapperScan("com.jiabowen.store.mapper")
public class StoreApplication {

    public static void main(String[] args) {
        SpringApplication.run(StoreApplication.class, args);
    }

    @Bean
    public MultipartConfigElement getMultipartConfigElement(){
        //Create a Configured Factory Class Object
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //Set up information about the object you want to create
        factory.setMaxFileSize(DataSize.of(10, DataUnit.MEGABYTES));
        factory.setMaxRequestSize(DataSize.of(15, DataUnit.MEGABYTES));
        //Create a MultipartConfigElement object from a factory class
        return factory.createMultipartConfig();
    }    
}

5.2 Display Avatar

Submit the file through an ajax request on the page, return a json string after submission, parse the data from the data, and set it to the src attribute of the img Avatar tag.

  • serialize(): form data can be automatically stitched into a key = value structure for submission to the server, typically data from common control types (text/password/radio/checkbox) and so on.

  • FormData class: Transfers data by keeping the data in the form in its original data structure

    new FormData($("from")[0])//Data of file type can be stored using FormData object
    
  • ajax handles data as a string by default, and submits data as a string by default, turning off these two default functions

    processData: false//How to process data, turn off processing data
    contentType: false//Form of submission of data
    

5.3 Display avatar after landing

You can update the avatar successfully, save the mailbox returned by the server in the client cookie object, and then detect each time the user opens the upload Avatar page, where the ready() method is used to automatically detect and read the avatar in the cookie and set it to the src property.

1. Set the value in the cookie:

Import cookies. JS file

<script src="../bootstrap3/js/jquery.cookie.js" type="text/javascript" charset="utf-8"></script>

Call cookie method

$.cookie("avatar",json.data.avatar,{expires: 7})//Unit: Days

2. On upload. The HTML page starts with cookies. JS file

<script src="../bootstrap3/js/jquery.cookie.js" type="text/javascript" charset="utf-8"></script>

3. On upload. The HTML page automatically reads the data in the cookie through ready().

$(document).ready(function () {
    let avatar = $.cookie("avatar");
    console
    //Get the cookie value to set to the src property of the Avatar
    $("#img-avatar").attr("src",avatar)
});

5.4 Display the latest Avatar

After changing the avatar, save the latest avatar address to the cookie again, and the same name will overwrite the original cookie

$.cookie("avatar",json.data,{expires: 7})

Keywords: Spring Boot

Added by dbo on Tue, 01 Feb 2022 19:55:08 +0200