基于SpringBoot-上传照片保存到本地,且回显照片

本文介绍如何使用SpringBoot实现照片上传至本地及数据库记录,包括PhotoController控制层方法、前端文件上传表单设计及本地照片展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:如何在数据库保存照片

将照片上传到本地后,数据库只需要保存照片名字即可(此名字是本地保存的文件的名字,通过UUID去重的名字,并不是展示照片时的照片名)。
数据表:
在这里插入图片描述文件保存在本地:
在这里插入图片描述

2:控制层方法

**PhotoController:**SpringBoot的文件上传比较方便不需要引入其它依赖。通过SpringInitializr选择web,thymeleaf等场景即可。

@Controller
public class PhotosController {

    @Autowired
    private PhotosService photosService;

    
    //负责跳转到主页,展示照片
    @RequestMapping("/")
    public String index(Model model){

        List<Photo> photos = photosService.list();

        model.addAttribute("photos",photos);

        return "index";
    }
    
    //负责跳转到添加照片页
    @RequestMapping("/up")
    public String up(){
        return "up";
    }
    
    
    //负责保存照片到本地
    @PostMapping("/upload")
    public String upLoad(@RequestParam("photoName")String name, @RequestPart("photo") MultipartFile photo) throws IOException {

        String fileName = null;

        if(!photo.isEmpty()){
            //获取源照片名
            String originalFilename = photo.getOriginalFilename();
            //获取照片后缀名
            String suffixName=originalFilename.substring(originalFilename.lastIndexOf('.'));
            //使用UUID
            fileName= UUID.randomUUID().toString()+suffixName;
            //保存照片到磁盘
            photo.transferTo(new File("选择自己保存的路径(注意后面的//不要缺少)//"+fileName));
        }
			//创建photo对象
        Photo p=new Photo(null,name,fileName);
			//保存到数据库
        photosService.save(p);

        //重定向到照片展示页面
        return "redirect:/";
    }
}

3:前端文件上传表单

文件上传需要post, enctype="multipart/form-data"支持。

 <form  th:action="@{/upload}" method="post" enctype="multipart/form-data">
        <div>
            照片名:<input type="text" name="photoName">
        </div>
        <div>
            照片:<input type="file" name="photo">
        </div>
        <button type="submit">提交</button>
    </form>

4:前端如何获取本地照片

创建并配置application.yaml: 通过spring.web.resources.static-locations配置本地访问路径

spring:
  servlet:
    multipart:
      max-file-size:  10MB   
      max-request-size:  100MB  
  web:
    resources:  
      static-locations:  file:自己选择保存的路径(注意后面的/不要缺少)/

前端展示照片: 这里使用thymeleaf的视图解析器,通过 <img th:src="@{/{path}(path=${p.path})}" width="20%" height="20%">访问到本地照片。
实际访问路径:http://localhost:8080/文件名

<table border="1px" cellpadding="0" cellspacing="0">
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Photo</th>
                </tr>
                <tr th:each="p:${photos}">
                    <td th:text="${p.id}"></td>
                    <td th:text="${p.name}"></td>
                    <td>
                        <img th:src="@{/{path}(path=${p.path})}" width="20%" height="20%">
                    </td>
                </tr>
        </table>

5:效果

之前ssm框架整合,也尝试了照片上传加回显,不过之前未将照片保存在本地,而是保存在服务器上,只要清理target照片就会丢失,这次保存到本次,比上次稳定点。
在这里插入图片描述

以下是一个基于Spring Boot的图片上传回显的代码实现示例,其中使用了Thymeleaf模板引擎: 1. 配置文件中添加文件上传配置: ```yaml spring: servlet: multipart: max-file-size: 10MB # 文件大小限制 max-request-size: 10MB # 请求大小限制 file-size-threshold: 2KB # 临时文件大小限制 ``` 2. 控制器中添加上传回显的方法: ```java @Controller public class ImageController { // 上传图片页面 @GetMapping("/upload") public String uploadPage(Model model) { model.addAttribute("image", new Image()); return "upload"; } // 上传图片回显 @PostMapping("/upload") public String uploadImage(@ModelAttribute("image") Image image, BindingResult result) throws IOException { if (result.hasErrors()) { return "upload"; } // 保存图片本地文件系统 byte[] bytes = image.getFile().getBytes(); Path path = Paths.get("images/" + image.getFile().getOriginalFilename()); Files.write(path, bytes); // 设置图片URL image.setUrl("/images/" + image.getFile().getOriginalFilename()); return "redirect:/upload"; } } ``` 3. 在Thymeleaf模板中添加上传表单及回显图片: ```html <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Image Upload</title> </head> <body> <h1>Image Upload</h1> <!-- 上传表单 --> <form action="#" th:action="@{/upload}" th:object="${image}" method="post" enctype="multipart/form-data"> <div> <label for="file">Choose an image:</label> <input type="file" id="file" name="file" accept="image/*" required="required" th:field="*{file}" /> </div> <div> <button type="submit">Upload</button> </div> </form> <!-- 回显图片 --> <div th:if="${image.url != null}"> <img th:src="@{${image.url}}" alt="Uploaded image" /> </div> </body> </html> ``` 其中,Image类用于封装上传的文件和回显图片URL: ```java public class Image { private MultipartFile file; private String url; // getters and setters } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值