目录
一、创表
mysql表存URL
create table test(
url varchar(255) comment 'http地址'
);
二、pom
<dependencies>
<!-- Spring起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!-- 图片上传 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.17</version>
</dependency>
</dependencies>
二、yaml配置
spring:
servlet:
# 表单上传文件大小限制
multipart:
enabled: true # 开启文件上传
max-file-size: 20MB # 设置上传文件最大值
max-request-size: 20MB # 设置上传文件总值
# 配置数据库连接
datasource:
name: test #数据库名
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false #url
username: root #用户名
password: root #密码
driver-class-name: com.mysql.jdbc.Driver #数据库链接驱动
# 服务配置
server:
port: 80
#文件上传配置
uploadPath:
# 图片保存物理真实目录路径,Windows默认C盘根目录,Linux默认根目录(../)
realFolder: /media/web/imgLogo/
# 图片反射的虚拟路径:列如http://localhost/upload/logo/xxx.jpg
reflexFolder: /upload/logo/
# Mybatis-Plus 数据库框架
mybatis:
mapper-locations: classpath*:mapper/**/*Mapper.xml # 配置mapper的扫描,找到所有的mapper.xml映射文件
type-aliases-package: com.example.uploadfile.entity # 搜索指定包别名---配置实体类
# config-location: classpath:mybatis-config.xml # 加载全局参数配置文件,config-location不能与configuration同时使用,否则会报错
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 日志输出到控制台,,定MyBatis所用日志的具体实现
cache-enabled: false # 关闭缓存,全局性地开启或关闭所有映射器配置文件中已配置的任何缓存,默认值为true
map-underscore-to-camel-case: true # 全局性地开启或关闭所有映射器配置文件中已配置的任何驼峰命名规则,默认值为false
auto-mapping-behavior: full # 指定MyBatis应该如何自动映射列到字段或属性,默认值为PARTIAL(属性类型有:NONE, PARTIAL, FULL)NONE:表示关闭自动映射、PARTIAL:只会自动映射没有定义嵌套结果映射的字段、FULL:会自动映射任何复杂的结果集(无论是否嵌套)
use-generated-keys: false # 指定是否使用自增主键,默认值为false
default-executor-type: reuse # 指定MyBatis的默认执行器类型,默认值为REUSE(重用)、BATCH(批量)、SIMPLE(简单)、CUSTOMIZE(自定义)
default-fetch-size: 100 # 指定MyBatis的默认查询结果集大小,默认值为100 (每次查询结果集的最大行数)设置较大的fetchsize,对性能会有很大的提升,Fetchsize设置大于返回的记录数时,对于性能的提升没有任何的意义,反而会增加内存的开销,导致内存溢出,请根据实际情况设置。
三、 实体
//添加可以不需要实体,查询的话需要用java对象 来 映射mysql数据,就是数据绑定,添加不用
public class TestBean {
private String httpUrl;
}
四、mapper
@Mapper
public interface TestMapper {
//添加URL
int addUrl(@Param("httpUrl") String url);
}
五、service
public interface TestService {
//添加URL
int addUrl(String url);
}
六、service实现类
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
public int addUrl(String url) {
return testMapper.addUrl(url);
}
}
七、controller
@RestController
public class TestController {
/**
* Servlet请求域对象
*/
@Autowired
private HttpServletRequest request;
/**
* 注入数据层添加URL业务接口
*/
@Autowired
private TestService testService;
/**
* 保存物理真实目录路径
*/
@Value("${uploadPath.realFolder}")
private String logoRealFolderPath;
/**
* 反射虚拟路径
*/
@Value("${uploadPath.reflexFolder}")
private String uploadReflexPath;
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam(value = "imgFile") MultipartFile imgFile) throws IOException {
if (imgFile != null && !imgFile.isEmpty()) {
//获取文件名
String filename = imgFile.getOriginalFilename(); //图片名
String[] split = new String[0];
if (filename != null) {
split = filename.split("\\.");
}
//只接受jpg、png、jpeg格式图片文件,其它格式的文件可按需添加判断,主要是为了防止上传恶意文件,加强安全性
if ("jpg".equalsIgnoreCase(split[1]) || "png".equalsIgnoreCase(split[1]) || "jpeg".equalsIgnoreCase(split[1])) {
//图片重命名加后缀
String photoName = UUID.randomUUID().toString().replace("-", "") + "." + split[1];
File destFile = new File(logoRealFolderPath + File.separator + photoName);
//判断是否存在, 不存在就创建
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
//压缩图片保存
Thumbnails.of(imgFile.getInputStream()).scale(0.8).toFile(destFile);
//获取协议、服务器IP、端口号、工程路径
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
String httpUrl = basePath + uploadReflexPath + photoName;
System.out.println("完成URL地址 = " + httpUrl);
//获取到URL后,可以将URL保存到数据库中,以便后续使用,这里就不做演示了,使用Mybatis即可
if (testService.addUrl(httpUrl) == 0) {
return "保存URL到数据库失败";
} else {
return "保存URL到数据库成功,文件地址为:" + httpUrl;
}
}
}
return "请上传文件后重试";
}
}
八、路径WEB映射配置类
public class MyWebConfigure implements WebMvcConfigurer {
/**
* 保存物理真实目录路径
*/
@Value("${uploadPath.realFolder}")
private String logoRealFolderPath;
/**
* 反射虚拟路径
*/
@Value("${uploadPath.reflexFolder}")
private String uploadReflexPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//addResourceHandler()配置需要映射的文件夹
//addResourceLocations()配置文件夹在系统中的路径,使用绝对路径,格式为“file:你的路径”
//registry.addResourceHandler(logoRealFolderPath + "**").addResourceLocations("file:C:\\zy\\upload\\");
registry.addResourceHandler(uploadReflexPath + "**").addResourceLocations("file:" + logoRealFolderPath);
}
}
九、Mapper映射SQL文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.uploadfile.mapper.TestMapper">
<insert id="addUrl" parameterType="string">
insert into test(url) values (#{httpUrl});
</insert>
</mapper>
十、post接口测试文件上传效果
(1)无上传文件时
(2)有上传文件
说明:这里是用localhost,访问链接是打不开的,需要测试最终效果的话,各位同学maven打包成jar,上传Linux云服务器运行SpringBoot项目,将测试步骤的localhost改为公网IP或者域名再上传图片,数据库就存了外网能访问的图片了,这里就不展示这些操作了,有兴趣的话去试试,我通过以上步骤,开发接口,在Android端打开相册选择图片已经实现外网调取url,Glide加载图片成功了
十一、总结
仅自己学习记录,如有错误,敬请谅解~,谢谢~~