配置文件:
# 声明图片的绝对路径和相对路径
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