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照片就会丢失,这次保存到本次,比上次稳定点。
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐