java springboot+thymeleaf 实现图片上传并展示到页面当中

thymeleaf模板的使用方法:
引入依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

xmlns:th="http://www.thymeleaf.org用于引入thymelaeaf模板引擎,yh是模板提供的标签,th:href用于引入外链的样式文件,th:text用于动态显示文本内容

<html lang="en" xmlns:th="http://www.thymeleaf.org">

先在配置文件当中编写文件上传的路径:

file.upload.path=D://program/Springbootstudentsystem/src/main/resources/static/
file.upload.path.relative=/static/**

创建一个MyWebAppConfigurer java文件实现WebMvcConfigurer接口, 配置资源映射路径

package com.example.springbootstudentsystem;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 资源映射路径
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {

    /**上传地址*/
    @Value("${file.upload.path}")
    private String filePath;
    /**显示相对地址*/
    @Value("${file.upload.path.relative}")
    private String fileRelativePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(fileRelativePath).
                addResourceLocations("file:/" + filePath);
    }
}

编写一个Controller类

package com.example.springbootstudentsystem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@CrossOrigin
@Controller
public class test {

    /**上传地址*/
    @Value("${file.upload.path}")
    private String filePath;

    // 跳转上传页面
    @RequestMapping("test")
    public String test() {
        return "test";
    }

    // 执行上传
    @RequestMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) {
        // 获取上传文件名
        String filename = file.getOriginalFilename();
        // 定义上传文件保存路径
        String path = filePath+"images/";
        // 新建文件
        File filepath = new File(path, filename);
        // 判断路径是否存在,如果不存在就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        try {
            // 写入文件
            file.transferTo(new File(path + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将src路径发送至html页面
        model.addAttribute("filename", "/static/images/"+filename);
        return "test";
    }

}

效果如下:

在这里插入图片描述

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现这个需求,我们可以采用以下步骤: 1. 创建一个登陆页面,用户在该页面输入用户名和密码以进行登陆。例如,我们可以创建一个名为`login.html`的Thymeleaf模板文件。 2. 创建一个Controller处理用户登陆请求。该Controller应该包含两个方法,一个用于显示登陆页面,另一个用于处理用户提交的登陆请求。在处理登陆请求时,我们需要检查用户输入的用户名和密码是否正确。如果正确,则将用户信息存储到Session,并重定向到主页。 3. 创建一个主页,用于显示当前用户的头像。例如,我们可以创建一个名为`index.html`的Thymeleaf模板文件。 4. 在主页,我们需要通过Session获取当前用户的信息,包括用户名和头像。然后,我们可以将头像以图片的形式展示页面上。 下面是一个示例代码: 1. `login.html`模板文件: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <form action="/login" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username"> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password"> </div> <button type="submit">Login</button> </form> </body> </html> ``` 2. `UserController`类: ```java @Controller public class UserController { @Autowired private UserService userService; @GetMapping("/login") public String showLoginPage() { return "login"; } @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password, HttpSession session) { User user = userService.login(username, password); if (user != null) { session.setAttribute("user", user); return "redirect:/"; } else { return "login"; } } } ``` 3. `index.html`模板文件: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Index</title> </head> <body> <h1>Welcome, <span th:text="${user.username}"></span>!</h1> <img th:src="@{/images/${user.avatar}}"/> </body> </html> ``` 在这个示例,我们通过Thymeleaf的`@{/}`表达式来加载头像图片。`${user.avatar}`表示当前用户的头像地址,`@{/images/}`表示图片资源的根路径。在实际应用,我们需要将用户头像上传到服务器,并将头像地址保存到数据库
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值