Spring Boot 实现图片上传并回显功能

一、常规形式

1 项目结构

Spring Boot 实现图片上传并回显功能_第1张图片

2 配置文件及环境设置

(1)配置文件

# 应用服务 WEB 访问端口
server.port=8080
# spring 静态资源扫描路径
spring.resources.static-locations=classpath:/static/
# 访问template下的html文件需要配置模板
spring.thymeleaf.prefix.classpath=classpath:/templates/
# 是否启用缓存
spring.thymeleaf.cache=false
# 模板文件后缀
spring.thymeleaf.suffix=.html
# 模板文件编码
spring.thymeleaf.encoding=UTF-8
#上传的绝对路径
file.upload.path=G://images/     #最关键#
#绝对路径下的相对路径
file.upload.path.relative=/images/**      #最关键#
#设置文件最大值
spring.servlet.multipart.max-file-size=5MB

在相关路径新建文件夹

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lxFge7I3-1625452749715)(C:\Users\17122\AppData\Roaming\Typora\typora-user-images\image-20201106192605478.png)]

3 代码

(1)pom.xml


     org.springframework.boot
     spring-boot-starter-thymeleaf


     org.springframework.boot
     spring-boot-starter-web

(2)index.html




    
    Title



[[${filename}]]
图片

(3)TestController.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

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

@Controller
public class TestController {

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

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

    // 执行上传
    @RequestMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) {
        // 获取上传文件名
        String filename = file.getOriginalFilename();
        // 定义上传文件保存路径
        String path = filePath + "rotPhoto/";
        // 新建文件
        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", "/images/rotPhoto/" + filename);
        return "index";
    }
}

(4)MyWebAppConfigurer

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);
    }
}

4 测试

Spring Boot 实现图片上传并回显功能_第2张图片

二、增加异步操作

1 前端ajax


2 后端Controller

@ResponseBody
@RequestMapping("/upLoad")
public String upLoadImage(@RequestParam("file") MultipartFile file) {
    // 获取上传文件名
    String filename = file.getOriginalFilename();
    String suffixName = filename.substring(filename.lastIndexOf("."));
    // 定义上传文件保存路径
    String path = filePath + "images/";
    //生成新的文件名称
    String newImgName = UUID.randomUUID().toString() + suffixName;
    // 新建文件
    File filepath = new File(path, newImgName);
    // 判断路径是否存在,如果不存在就创建一个
    if (!filepath.getParentFile().exists()) {
        filepath.getParentFile().mkdirs();
    }
    try {
        // 写入文件
        file.transferTo(new File(path + File.separator + newImgName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "/images/images/" + newImgName;
}

到此这篇关于Spring Boot 实现图片上传并回显功能的文章就介绍到这了,更多相关Spring Boot上传图片回显内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(Spring Boot 实现图片上传并回显功能)