一、属性资源文件与类映射
一些公用的属性,可以放在配置文件中。因为如果有测试环境、预发布环境、生产环境的话,那么相同类扥属性,每一个环境都要配置一份,其他的需要注释掉。来回 切换环境的话,操作效果不好。
- 编写配置文件
- 编写配置文件对应的java类
package com.imooc.resource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "file")
@PropertySource("classpath:file-upload-prod.properties")
public class FileUpload {
private String imageUserFaceLocation;
private String imageServerUrl;
public String getImageServerUrl() {
return imageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.imageServerUrl = imageServerUrl;
}
public String getImageUserFaceLocation() {
return imageUserFaceLocation;
}
public void setImageUserFaceLocation(String imageUserFaceLocation) {
this.imageUserFaceLocation = imageUserFaceLocation;
}
}
file.imageUserFaceLocation=/workspaces/images/foodie/faces
file.imageServerUrl=http://localhost:8088/foodie/faces
二、为静态资源提供网络映射服务
package com.imooc.config;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
// 实现静态资源的映射
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/") // 映射swagger2
.addResourceLocations("file:/workspaces/images/"); // 映射本地静态资源
}
//http://localhost:8088/doc.html
//http://localhost:8088/foodie/faces/20030258GG370ZR4/face-20030258GG370ZR4.png
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
}
三、上传图片
四、限制大小并自定义捕获异常
application.yml
spring:
servlet:
multipart:
max-file-size: 512000 #文件上传大小限制为500KB
max-request-size: 512000 #请求大小限制为500KB
自定义异常类:
package com.imooc.exception;
import com.imooc.utils.IMOOCJSONResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
@RestControllerAdvice
public class CustomExceptionHandler {
// 上传文件超过500k,捕获异常:MaxUploadSizeExceededException
@ExceptionHandler(MaxUploadSizeExceededException.class)
public IMOOCJSONResult handlerMaxUploadFile(MaxUploadSizeExceededException ex) {
return IMOOCJSONResult.errorMsg("文件上传大小不能超过500k,请压缩图片或者降低图片质量再上传!");
}
}