之前商城的商品都是通过数据库直接导入数据,商品图片是配置好的。现在想进一步完善功能,增加商品上传的功能,包括商品的名称价格数量,和商品的图片信息,类似于后台管理。和一起一样前台页面简洁能用就行,写了一个非常粗糙的界面,粗糙到不好意思拿出来看,但功能已经满足
图片服务器这里用的fastdfs,之前再虚拟机搭建过一次fastdfs+nginx,后来换了电脑再打一遍嫌麻烦,改用docker搭建了,参考的这篇博客不得不说用docker是真的方便,下面说一下流程
图片上传
第一步先上传图片到fastdfs,会返回一个了路径,该路径我保存在页面的一个隐藏的input,用作和商品信息一起提交
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.2</version>
</dependency>
yml配置
fdfs:
so-timeout: 1501 # 超时时间
connect-timeout: 601 # 连接超时时间
thumb-image: # 缩略图
width: 60
height: 60
tracker-list: # tracker地址:你的虚拟机服务器地址+端口(默认是22122)
- 192.168.109.201:22122 fastdfs服务器地址
controller代码
@PostMapping("/image")
public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file){
String url = this.uploadService.upload(file);
if (StringUtils.isBlank(url)) {
return ResponseEntity.badRequest().build();
}
return ResponseEntity.ok(url);
}
service代码
public String upload(MultipartFile file) {
String originalFilename = file.getOriginalFilename();
// 校验文件的类型
String contentType = file.getContentType();
if (!CONTENT_TYPES.contains(contentType)){
// 文件类型不合法,直接返回null
LOGGER.info("文件类型不合法:{}", originalFilename);
return null;
}
try {
// 校验文件的内容
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
if (bufferedImage == null){
LOGGER.info("文件内容不合法:{}", originalFilename);
return null;
}
// 保存到服务器
// file.transferTo(new File("F:\\tmp\\img\\" + originalFilename));
String ext = StringUtils.substringAfterLast(originalFilename, ".");
StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
// 生成url地址,返回
LOGGER.info(storePath.getFullPath());
return "http://image.leyou.com/" + storePath.getFullPath();
} catch (IOException e) {
LOGGER.info("服务器内部错误:{}", originalFilename);
e.printStackTrace();
}
return null;
}
图片上传之后会返回地址:group1/M00/00/00/wKhtyV8F0LKAe2upAAa9V3dy2Nw060.JPG
该地址是可以直接访问的,这说明上传成功
提交商品信息
数据库中我创建了两张表,一张用来保存商品信息,另一张用来保存图片地址,考虑到一个商品会上传多张图片,用一对多的方式关联
这样商品信息和图片就上传完毕了,后面商品列表就可以从数据库动态读取了