一、构建公用项目
1.1 新建maven项目
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.woniuxy.ticket</groupId>
<artifactId>ticket-common</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
</dependency>
</dependencies>
</project>
公共工具类:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseResult<T> {
private int statusCode; // 状态码:后台处理的结果
private String message; // 消息,提示用
private T data; // 返回的数据
public ResponseResult(int statusCode, String message) {
this(statusCode, message, null);
}
public ResponseResult<T> success(T data){
this.setStatusCode(200);
this.setMessage("success");
this.setData(data);
return this;
}
public ResponseResult<T> success(){
this.setStatusCode(200);
this.setMessage("success");
return this;
}
public ResponseResult<T> error(){
this.setStatusCode(500);
this.setMessage("fail");
return this;
}
}
1.2 在需要使用的项目maven中导入
<dependency>
<groupId>com.woniuxy.ticket</groupId>
<artifactId>ticket-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
二、文件上传(本地路径)
2.1 配置文件application.properties
server.port=9001
file.location=E://wn75_ticket_file
spring.resources.static-locations=classpath:static/,file:${file.location}
2.2 FileController
@RestController
@RequestMapping("/file")
public class FileController {
@Value("${file.location}")
private String fileLocation;
@PostMapping("/upload")
public ResponseResult upload(MultipartFile file){
//随机生成文件名
String fileName = UUID.randomUUID().toString().replaceAll("-","");
//截取后缀
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
File file1 = new File(fileLocation);
if(!file1.exists()){
file1.mkdirs();
}
File newFile = new File(file1,fileName+suffix);
try {
file.transferTo(newFile);
}catch (IOException e){
e.printStackTrace();
}
return new ResponseResult().success(fileName+suffix);
}
}
获取生成的fileName+suffix,将其填入img的src中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="8baae898dfbe4088b6b533eb961151ee.jpg" alt="" id="img">
</body>
</html>