简介:springboot项目作为后台入口,打成jar包后部署到linux服务器,通过url的方式访问服务器本地图片。
实现思路:
显示:后台用配置文件的方式建立url和本地图片的映射关系
上传:用流的方式上传
核心代码:
核心配置类:重点的baseImagePath,linux用绝对路径,路径最后一个文件夹后一定要加’/’,下面的baseImagePath写在了.yml配置文件里了,例:/home/nixinyan/apps/local/graduate/pic/
linux里的图片路径:
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Value("${image.baseImagePath}")
private String baseImagePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/api/file/**").addResourceLocations("file:"+baseImagePath);
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
for (int i = converters.size() - 1; i >= 0; i--) {
if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
converters.remove(i);
}
}
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.WriteMapNullValue,//是否输出值为null的字段
SerializerFeature.WriteNullListAsEmpty,//List字段如果为null,输出为[]
SerializerFeature.WriteNullStringAsEmpty,//字符类型字段如果为null,输出为"",而非null
SerializerFeature.WriteNullNumberAsZero,//数值字段如果为null,输出为0,而非null
SerializerFeature.WriteNullBooleanAsFalse//Boolean字段如果为null,输出为false,而非null
);
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
converters.add(fastJsonHttpMessageConverter);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路径
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOrigins("*")
// 是否允许证书 不再默认开启
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("*")
// 允许任意头
.allowedHeaders("*")
// 跨域允许时间
.maxAge(3600);
}
private CorsConfiguration corsConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
/* 请求常用的三种配置,*代表允许所有,当时你也可以自定义属性(比如header只能带什么,只能是post方式等等)
*/
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setMaxAge(3600L);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfig());
return new CorsFilter(source);
}
}
有了配置文件就可以先测试一下显示功能了
访问虚拟机地址+后端端口号+/api/file/+文件名
linux里的图片:
例:http://192.168.225.128:2048/api/file/011oct.jpg
图片上传功能则需要写代码,实例代码:
@PostMapping("/cover")
@ApiOperation(value = "上传图片封面")
DTO coversUpload(MultipartFile file) {
System.out.println("path:"+baseImagePath+",url:"+baseImageUrl);
File imageFolder = new File(baseImagePath);
File f = new File(imageFolder, StringUtil.getRandomString(6) + file.getOriginalFilename()
.substring(file.getOriginalFilename().length() - 4));
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
try {
file.transferTo(f);
} catch (IOException e) {
e.printStackTrace();
return new DTO(RetCodeEnum.FAIL);
}
String imgURL = baseImageUrl + f.getName();
System.out.println(imgURL);
return new DTO(RetCodeEnum.SUCCEED.getCode(), imgURL);
}
注:因为涉及文件操作,项目打包部署启动的时候要用sudo权限