基于 Spring Boot 瑞吉外卖系统开发(七)
新增菜品页面
菜品管理页面提供了一个“+新增菜品”按钮,单击该按钮时,会打开新增菜品页面。
菜品分类列表
首先要获取分类列表数据。
请求路径/category/list
,请求方法GET
,参数type
。
在CategoryController
类中添加获取分类列表方法。
@GetMapping("/list")
public R<List<Category>> list(Integer type){
QueryWrapper<Category> query = new QueryWrapper<>();
query.eq("type",type);
List<Category> list = categoryService.list(query);
return R.success(list);
}
运行效果
菜品图片上传
上传的UI,点击“上传图片”选择本地图片上传。
请求路径/common/upload
,请求方法POST
,参数file
。
在application.yml
配置文件存储路径。
reggie:
path: D:\file\img\
在com.itheima.reggie.controller
创建CommonController类,并添加文件上传下载方法。
使用@value注入配置文件存储路径。
@RestController
@RequestMapping("/common")
public class CommonController {
@Value("${reggie.path}")
private String basePath;
/**
* 文件下载
*/
@GetMapping("/download")
public void download(String name, HttpServletResponse response) throws IOException {
response.sendRedirect("/images/"+name);
}
/**
* 图片上传
*/
@PostMapping("/upload")
public R<String> upload(MultipartFile file){
//获取上传的原始图片名
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//使用UUID重新生成图片的名称,防止文件名称重复造成图片覆盖
String fileName = UUID.randomUUID().toString() + suffix;
//创建一个目录对象
File dir = new File(basePath);
//判断当前目录是否存在
if(!dir.exists()){
//目录不存在,则创建
dir.mkdirs();
}
try {
//将上传的图片转存到指定位置
file.transferTo(new File(basePath + fileName));
} catch (IOException e) {
e.printStackTrace();
}
return R.success(fileName);
}
}
运行测试
图片上传和展示测试。