Dubbo整合SpringCloud图片显示问题
Tips:公司项目,记录一点经验吧,理解的不对的地方欢迎大神指点
问题:商品图片上传功能(公司没有专门文件服务器)写的保存目录直接是保存在docker容器内部目录下,做的docker外部存储映射到服务器某个文件夹下面(因为怕镜像升级啊什么的 导致图片丢失)。下面粘贴一下
Jenkins配置(外部存储设置 Jenkins构建自动设置)
SpringBoot设置docker容器新增文件夹配置
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.4.13</version>
<configuration>
<dockerHost>http://0.0.0.0:2375</dockerHost>
<imageName>${docker.image.prefix}/${project.artifactId}</imageName>
<imageTags>
<imageTag>${project.version}</imageTag>
<imageTag>latest</imageTag>
</imageTags>
<baseImage>frolvlad/alpine-oraclejdk8:slim</baseImage>
<volumes>/product-images</volumes>
<entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
这样实际图片上传路径指定/product-images图片上传问题就解决了
问题2:因为图片直接存储在数据库的是相对路径就是比如(/20180909/image.png)实际项目是在docker容器中,图片也是在/product-images 。我返回给前端的文件路径就是这样的 www.域名/Zool/product-images/20180909/image.png 导致找不到图片,在测试服务器上还没发现问题因为测试机有缓存所以导致了这个问题的一个隐藏,今天打正式版导致图片不显示。
思路:项目是SpringBoot 目前我知道的 放到resource目录下 文件直接项目 然后相对路径是能读取到图片的 但是放到docker下,而且也没在resource下,(跟docker没关系)就相当于读机器上某个文件导致的不让读取。
解决办法:
https://域名/Zool/seeImage?imgPath=/product-images" + catalogProductDto.getImages()
@RequestMapping(value = "/seeImage",method = RequestMethod.GET)
public String seeImage(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "imgPath") String imgPath ) {
try {
FileInputStream hFile = new FileInputStream(imgPath);
//得到文件大小
int i = hFile.available();
byte data[] = new byte[i];
//读数据
hFile.read(data);
response.addHeader("Content-Type",getContentType(imgPath));
response.addHeader("Accept-Ranges","bytes");
//得到向客户端输出二进制数据的对象
OutputStream toClient = response.getOutputStreStream();
//输出数据
toClient.write(data);
toClient.flush();
toClient.close();
hFile.close();
return "";
}
catch (Exception ex)
{
ex.printStackTrakTrace();
return "处理失败"+ex.getMessage();
}
}
/**
* 获取后缀
* @return
*/
private String getContentType(String imgPath) {
String resultSuffix = "";
try{
String suffix = imgPath.substring(imgPath.lastIndexOf('.'));
System.out.println("url中的文件扩展名:"+ suffix);
if(".jpg".equals(suffix)){
resultSuffix = "image/jpeg";
}
if(".png".equals(suffix)){
resultSuffix = "image/png";
}
}catch (Exception e){
e.printStackTrakTrace();
return "处理失败" + e.getMessage();;
}
return resultSuffix;
}
逻辑:后台传给前台一个请求路径,前台请求调用后台的加载图片方法,图片加载以流的方式返回给前台展示 这个问题解决