分布式图片上传代码
首先在根文件下创建图片上传的小模块。
首先创建项目
1.
2 导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
我这里是继承了父文件的依赖所以没有版本号,若没有继承父文件依赖的同学,请把版本号加上。
项目结构:
- 创建启动类
编写启动类代码:
@SpringBootApplication
@EnableDiscoveryClient
public class LyUploadService {
public static void main(String[] args) {
SpringApplication.run(LyUploadService.class,args);
}
}
编写application.yml 配置文件
server:
port: 8082
spring:
application:
name: upload-service
servlet:
multipart:
max-file-size: 5MB #限制文件上传大小
#Eureka
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
lease-renewal-interval-in-seconds: 5 #每隔5s发送一次心跳
lease-expiration-duration-in-seconds: 10 #10s不发送就过期
prefer-ip-address: true
ip-address: 127.0.0.1
instance-id: ${spring.application.name}:${server.port}
编写service代码:
@Service
@Slf4j
public class UploadService {
//支持的文件类型
private static final List<String> suffixes = Arrays.asList("image/png","image/jpeg");
public String upload(MultipartFile file){
try {
//1、图片信息校验
//1)获取校验图片类型
String contentType = file.getContentType();
if(!suffixes.contains(contentType)){
log.info("上传失败,文件类型不匹配:{}",contentType);
return null;
}
//2)校验图片内容
BufferedImage image = null;
image = ImageIO.read(file.getInputStream());
if (image == null){
log.info("上传失败,文件内容不符合要求");
return null;
}
//2. 保存图片
//1)生成保存目录
File dir = new File("D:\\code\\upload");
if(!dir.exists()){
dir.mkdirs();
}
//2) 保存图片
file.transferTo(new File(dir,file.getOriginalFilename()));
//3) 拼接图片地址
String url = "http://image.empty.com/upload/"+file.getOriginalFilename();
return url;
} catch (Exception e) {
return null;
}
}
}
编写controller层
@RestController
@RequestMapping("upload")
public class UploadController {
@Autowired
private UploadService uploadService;
@PostMapping("image")
public ResponseEntity<String> uploadImage(@RequestParam("file")MultipartFile file){
String url = this.uploadService.upload(file);
if(StringUtils.isBlank(url)){
//url为空,证明上传失败
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
//返回200,并且携带url路径
return ResponseEntity.ok(url);
}
}
编写application.yml 添加路由忽略
zuul:
ignored-services:
- upload-service # 忽略upload-service服务
配置nginx中的host
server {
listen 80;
server_name api.leyou.com;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 上传路径的映射
location /api/upload {
proxy_pass http://127.0.0.1:8082;
proxy_connect_timeout 600;
proxy_read_timeout 600;
rewrite "^/api/(.*)$" /$1 break;
}
location / {
proxy_pass http://127.0.0.1:10010;
proxy_connect_timeout 600;
proxy_read_timeout 600;
}
}
使用Cors去解决跨域问题,在模块api-gateway下创建一个config包,把一下代码放在此包下面。
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允许的域,不要写*,否则cookie就无法使用了
config.addAllowedOrigin("http://manage.leyou.com");
//2) 是否发送Cookie信息
config.setAllowCredentials(false);
//3) 允许的请求方式
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("POST");
config.addAllowedHeader("*");
//2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}