thymeleaf 使用图片url或者上传本地图片

配置文件:

# 声明图片的绝对路径和相对路径
file.upload.path=F://images/
file.upload.path.relative=/images/**

配置类:

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

//继承WebMvcConfigurer扩展mvc
//用于往容器中添加组件
@Configuration
public class MyMvcConfig 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);
    }
}

实体类Picture.java

package com.ckh.springboot04.entities;


import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.Date;

@Entity
@Data
@Table(name = "pic_info")
@EntityListeners(AuditingEntityListener.class)
public class Picture {

    @Id
    @GeneratedValue
    private Integer picId;
    private String picUrl;//轮播图源地址
    private String picDesc;//图片描述

    @CreatedDate//自动添加创建时间的注解
    private Date createTime;
    @LastModifiedDate//自动添加更新时间的注解
    private Date updateTime;
}

前端添加页面:
上传图片url或者本地选择图片:

	<!--图片url-->
<form th:action="@{/pic}" method="post" enctype="multipart/form-data">
	<div class="form-group">
		<label for="picUrl">图片源地址</label>
		<input name="picUrl" type="text" class="form-control" id="picUrl"
			   th:value="${pic} != null ? ${pic.picUrl}"
			   placeholder="url">
	</div>
	
	<!--上传本地图片-->
	<div class="form-group">
		<label for="uploadFile">或者 上传本地文件</label>
		<input type="file" class="form-control-file" id="uploadFile" name="imgFile">
	</div>
</form>

controller层:

/*
  * 添加图片
  * 接收picture参数,save进数据库,redirect到"/pictures"进行列表显示
  * */
  @PostMapping("/pic")
  public String addPic(Picture picture, @RequestParam("imgFile") MultipartFile file){
      System.out.println("接收到的图片信息:");
      System.out.println(picture);

      // 获取上传文件名
      String filename = file.getOriginalFilename();
      //选择上传本地文件,picture中picUrl='',需要将文件地址插入picUrl
      if (!"".equals(filename)){
          // 定义上传文件保存路径
          //String path = "F:\\java\\workspace\\spring-boot-04-web-restfulcrud\\src\\main\\resources\\static\\asserts\\img";
          String path = filePath + "uploadImages/";
          // 新建文件
          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();
          }

          //保存用于前端显示的picUrl
          //String picUrl = "http://localhost:8081/seller/asserts/img/" + filename;
          String picUrl = "/images/uploadImages/" + filename;
          picture.setPicUrl(picUrl);
      }

      Picture save = pictureRepository.save(picture);

      System.out.println("添加的图片:");
      System.out.println(save);
      return "redirect:/pictures";
  }

前端图片:

<!--图片显示-->
<td><img height="50" width="50" th:src="@{${pic.picUrl}}" alt=""></td>

注意!!th:src="@{${pic.picUrl}}",要想显示本地图片,src必须由@{}包裹!!

参考:https://www.cnblogs.com/zhainan-blog/p/11169163.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pink_soda

新手程序媛,感谢小主打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值