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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章